开发者

What is the scope of a char*[] in C?

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?


char *line[WORDLEN];

is an array of character pointers. I think what you meant it to be was:

char line[WORDLEN];

a single character array. I would just opt for:

while(some condition)
{
     char line[WORDLEN];
     line[0] = '\0';
     //do stuff to line, including strcat(line, "words")
     printf("%s", line);
}

since that guarantees the string will be empty each time through the loop before you start doing anything with it, and irrespective of scope rules.


In your code, you don't need an array of character pointers - you need an array of characters:

while (some condition)
{
     char line[WORDLEN];

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:

     char line[WORDLEN] = "";

or:

     char line[WORDLEN];
     line[0] = '\0';

Now you can safely do the commented operations, including (in particular) strcat(). (Well, that assumes you can do strcat() 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.)

     //do stuff to line, including strcat(line, "words")
     printf("%s", line);
     line[0] = '\0';

With the initialization at the start of the loop, this assignment at the end is superfluous.

}


You're redeclaring line each time you loop.

EDIT: And you're doing some weird stuff with the pointers. line is an array of char pointers in your declaration! Try this:

char line[WORDLEN];
while(some condition)
{
     line[0] = '\0';
     //do stuff to line, including strcat(line, "words")
     printf("%s", line);

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜