简体   繁体   中英

prep string array for strlen

I have a string array that is declared like this:

char *strs[MAX_STRINGS];

I add values incrementally to the array like this:

char buffer [MAX_LENGTH];
buffer = someFunctionThatReturnsAStringPointer();
strs[i] = malloc(sizeof(buffer)+1);
strcpy(strs[i],buffer);

I need to loop through array values that get added, stopping when I reach an index with no value, so strlen should work, but it keeps segfaulting whenever I hit an index that hasn't been set:

while(strlen(strs[i])!=0) //segfaults when it gets to an unset index

How do I initilize the strs array so that it doesn't segfault with strlen?

I tried memset(strs,0,MAX_STRINGS); but it messed a lot of things up (the strings were replaced with gibberish) and still segfaulted

This is wrong:

char buffer [MAX_LENGTH];
buffer = someFunctionThatReturnsAStringPointer();

You should change it to one of the two options below (preferably the second one).

Option #1:

char* buffer;
buffer = someFunctionThatReturnsAStringPointer();

Option #2:

char buffer [MAX_LENGTH];
someFunctionThatCopiesIntoBuffer(buffer);

As to your question, you can use memset(strs,0,MAX_STRINGS) , or simply iterate the strs array and set each entry to 0. But instead of testing strlen(strs[i])!=0 , you should test strs[i]!=0 .

Probably u can set all Pointers to NULL initially

for (i = 0; i < MAX_STRINGS; i++)
    strs[i] = NULL;

And check for

while (strs[i] != NULL) 

or just

while (strs[i])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM