Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with returning char[] from function 1

Status
Not open for further replies.

mattias1975

Programmer
Jul 26, 2004
36
0
0
SE
Hello!

I have a problem:

Code:
char[] function(){
	char str[10];
	strcpy(str, "Hello!");
	return str;
}

int main(){
	char str[10];
	str = function();
}

The compiler tells me: incompatible types in assignment.
How should i do instead to get it work?
 
A function can't return char[]; it must return char* (pointer to char array) in that case.
The function in your snippet returns a dead pointer to the(deallocated from a stack after return) local (so called automatic storage) array str. It's a typical error (not only for beginners, alas;)...
You can't assign a pointer to an array name variable. It's a constant (non-modified) pointer. You must declare char* variable in that case...
Don't uncheck Process TGML flag on the message form (see not pocessed CODE tags in your post).
 
Code:
char* function(){
char *str;
str = (char *) maloc(10);
if (!str)
    return NULL;
strcpy(str, "Hello!");
return str;
}

int main(){
char *str;
str = function();
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top