array of string
hi to all
I write the code below to search string in array for 6 times, if I input a string not exist in array more than one time first time it return not found and this true but then it print found although that's string not exist in array.
the error is here
I need to put the content of str in arr[ii] not to make arr[ii] point to location of str. how I can do that??
Re: array of string
arr doesn't store strings. It's of type char*, so it stores pointers only. If you want to store char data, you need a char array, not a pointer to char.
Here's the problem. Suppose str represents 512 bytes at memory location 1000. arr=str; sets arr to 1000. If str contains "hello", arr DOES NOT contain "hello", it's just a pointer. It contains 1000 and *currently* points to "hello". So now if you overwrite str so it now holds "goodbye" and do arr=str;, arr and arr will now both point at 1000 and when you dereference each they will both find "goodbye". arr never contained "hello", it only ever contained 1000, so it will point to whatever is at 1000, i.e. whatever is currently in str.
You always need to be careful with pointers in C. They're really easy, but you have to be aware what they're pointing at, and it's confusion over that which makes pointers appear difficult.
So the solution is to make arr a 2D array of strings, which you can do either with char *arr and a bunch of malloc statements (remember "free" so that you don't leak memory), or you can do char arr. arr=str then won't work; you'll have to do strcpy(arr,str).
|All times are GMT +5.5. The time now is 22:39.|