I'm a little stumped on a section of code in my program. I'm trying to take in a string of chars and then store each word within that string separately in an array of strings without using stdtok and then output them with only a single space separating each word, even if the two words were originally separated by more than one space in the input.. I have most of the code but I can't figure out how to how to load the string array after I add a null char after each word. Having a brain fart... Please help.

#include<stdio.h>
#include<string.h>

int main (void) 
{
   int i, j=0, count=0, length=0;
   char array_char[1023];
   char* array_str[512];	
	
   fputs("Type a string of words and then press 'Enter': ", stdout);
   fflush(stdout); 
   fgets(array_char, sizeof array_char, stdin);
	
   length = strlen(array_char);   // add (-1) to delete the newline
	
   printf(array_char);
   printf("\n");
	
   for(i=0; i<length; i++)
   {
	if(array_char[i] == ' ')
	{
	   array_char[i] = '\0';
	   do
	   {
		i++;
	   }
	   while(array_char[i] == ' ');
	}
	else
	{
	   continue;
	}
   }
	
	
   //add code here (without using stdtok) that loads each word in the string (until it encounters a null) into an array of strings.
   //increment 'count' each time
	
	
   for (i = count; i >= 0; i--) //yes I'm outputting them in reverse on purpose
   {
      printf("%s ", array_str[i]);
   }
      printf("\n");
	
   return 0;
}

Dani AI

Generated

A concise wrap-up and a safe, practical way to finish loading the words into array_str.

was on the right track: tokenize the input in place (turn runs of spaces into '\0') and record the start address of each word in the pointer array. After you remove the trailing newline and convert runs of spaces to '\0' (your loop already does that), a single forward scan will find every word start; store pointers only when you see a non-null character that either is at index 0 or follows a '\0'. Keep a bounds check so count never exceeds the array_str capacity.

A simple, robust example of the scanning + reverse printing (different from the code already posted) looks like this:

/* assume newline already removed and runs of spaces -> '\0' */
int w = 0;
for (int p = 0; p < length; ++p) {
    if (array_char[p] != '\0' && (p == 0 || array_char[p-1] == '\0')) {
        if (w < 512) array_str[w++] = array_char + p;
    }
}
for (int k = w - 1; k >= 0; --k) {
    printf("%s", array_str[k]);
    if (k) putchar(' '); else putchar('\n');
}

Troubleshooting and cautions: do not use printf(array_char) (format-string vulnerability) — always use printf("%s", ...). When printing reversed, start from count - 1 to avoid an off-by-one and negative indexing. Check for empty input (w == 0) before printing. Remember pointers in array_str reference the original buffer; if you need persistent separate strings, duplicate them with strdup/malloc and strcpy. This approach complements ’s suggestion and should fill the gap you mentioned when loading the pointer array; ’s final post indicates a working variation was chosen, but the pattern above is a clear, safe template to follow.

Recommended Answers

All 2 Replies

You can do it all in the first for loop. All you need to do is save the start of a word in the array_str like array_str[j++] = &array_char[i]; and insert the '\0' as you are doing.

Here is a way to get rid the '\n'.

#include<stdio.h>
#include<string.h>
int main (void)
{
   int i, j=0,
       count=0, length=0,
       inWord=0;
   char array_char[1023];
   char* array_str[512];
   char *tmp;

   fputs("Type a string of words and then press 'Enter': ", stdout);
   fflush(stdout);
   fgets(array_char, sizeof array_char, stdin);
   // Get rid of the '\n' if there
   if ( (tmp = strchr(array_char,'\n') )){
      *tmp = '\0';
   }
   length = strlen(array_char);   // Now the newline is gone

   printf("%s\n",array_char);

Thank you. In the end I went a slightly different way but reading and playing around with your reply helped me to finally understand it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.