Reputation: 227
Whats wrong with this C code lines
char *string()
{
char *text[20];
strcpy(text,"Hello world");
return text;
}
I was poor at pointers and I have seen this in some previous paper. Can't able to solve.
Upvotes: 1
Views: 118
Reputation: 399753
It doesn't compile, since it treats an array of character pointers as a single array of characters.
The variable declaration line should be:
char text[200];
With that fix done, it's still broken for the reason you're probably interested in: it returns the address of a local variable (the text
character array) which goes out of scope as the function returns, thus making the address invalid. There are two ways around that:
static
, since that makes it live for as long as the program runs.malloc()
, but that transfers ownership to the caller and requires a call to free()
or memory will leak if this function gets called a lot.Also, as a minor point, its name is in a reserved name space (user programs cannot define functions whose names begin with str
). Also, a function taking no arguments should be declared as (void)
in C, an empty pair of parentheses does not mean the same thing.
Upvotes: 7
Reputation: 3272
This code will not compile because you are trying to make an array of pointers.
In simple words if you want to handle string using pointer you can do using following:
char *str="HELLO WORLD";
And if you want to handle string using char array you have to remove value at address operator(*).
here it is:
char text[20];
then you can perform your function.
Still there is error as the Scope of the text is only valid inside the function so if you want to pass address and retain the value make it static
static char text[20];
return text;
Upvotes: 2