I have some code that does the following:
while(some condition)
{
char *line[WORDLEN];
//do stuff to line, including strcat(line, "words")
printf("%s", line);
line[0] = '\0';
}
However, it seems like line[0] = ‘\0’ is not doing what I am hoping it will do. I want to go back through the loop, and use line as though it has just been declared. The loop works as desired the first time through, however fails to treat line as a new char*[] on subsequent iterations. Any idea as to why?
In your code, you don’t need an array of character pointers – you need an array of characters:
Now, each time through the loop, the variable line has indeterminate contents – in theory. In particular, on the first time through, it has no defined value. So, you should initialize it:
or:
Now you can safely do the commented operations, including (in particular)
strcat(). (Well, that assumes you can dostrcat()safely – which is possible as long as you know the length of the data already in the target string, the size of the target string buffer, and the length of the appended string, and have checked that there is enough space to store what you want. If you don’t know that there’s enough room, then you are heading for crashes.)With the initialization at the start of the loop, this assignment at the end is superfluous.