Reputation: 19
I have an assignment where I am required to pass an array of string pointers to a function, assign strings and then read back these strings. Here is what I am doing:
void getStr(char *str[])
{
char temp[256];
strcpy (temp,"Apple");
*str = temp;
printf("\ngetStr Str= %s",*str);
str++;
strcpy (temp,"Mango");
*str = temp;
printf("\ngetStr Str= %s",*str);
str++;
}
int main()
{
char *str[2] ;
int i=0;
getStr (str);
for(i =0 ;i<2;i++)
printf("\nstr addr =%x, str= %s\n",&str[i],str[i]);
return 1 ;
}
Here is my output:
getStr Str= Apple
getStr Str= Mango
str addr =28d623b0, str=
str addr =28d623b8, str=
So str gets the strings assigned correctly in getStr(), but when I print them in main() it is blank. What am I doing wrong here?
Upvotes: 0
Views: 806
Reputation: 31
This is very old post, but I must update it because I have similar problem, and I found out, that in side of function, I need use pointer only once, and array is restored like I am using this original from outside.
void getStr(char *str)
{
str[1] = (temp,"Apple");
str[2] = (temp,"Mango");
}
int main()
{
char str[2] ;
int i=0;
getStr (str);
for(i =0 ;i<2;i++)
printf(str[i]);
return 1 ;
}
That's why I hate use pointers, is to much mist-confusion and pointers it self are used in wrong way. They should be used only in special cases, like passing some arrays to function, to prevent making copy of this same twice. And Function it self don't need output set of values. But that's is only in special case. Using pointers on each line in program don't have sense if compiler is doing it anyway, From what I learned, pointers was design only because there was to much problems with functions and passing big sort of data.
Upvotes: 0
Reputation: 33607
This sort question seems to be coming up constantly.
void getStr(char *str[])
{
char temp[256];
...
}
That temp
array is a block of memory whose lifetime is tied to the duration of the getStr
function.
Also, when you overwrite it from "Apple" to "Mango", then the pointer you had stored that used to point to temp
in str[0] will point to "Mango". str[0] and str[1] hold the same pointer! And that pointer is no longer pointing to valid memory as soon as you return from the function. :-/
For these kinds of problems, C programmers use things like strdup. That does a memory allocation for each string and is a little bit more ergonomic than having to do strlen/malloc/strcpy. Either way, remember to free()
each string when you're done with them.
Upvotes: 0
Reputation: 137310
You stored into str
the address of the first element of the local variable temp
(the array decayed into a pointer), but that array's lifetime ends once getStr()
returns. Hence you are accessing a local variable after its lifetime ended, and undefined behavior results.
Upvotes: 1