C String is correct in one function and dumps garbage in the other
This is my code
#include <stdio.h>
void abc(char *text);
int main(void)
{
char text[20];
abc(text);
printf("text in main : %s\n",text);
return 0;
}
void abc(char *text)
{
text = "abc";
printf("text in abc function : %s开发者_开发百科\n",text);
}
And this is output.
text in abc function : abc
text in main : ฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬ๑ป ๚
My questions are:
- Why is the text variable in the main function and in the
abc
function is not the same? - I try to change to use
scanf
in theabc
function and it works! there are the same. Why? - How to modify the code to make it work. I means from question1 that make main function and in abc function are the same?
When you call the function:
abc(text);
a copy of the pointer text
is made, and this pointer is the one used in the function abc()
. So that when you say:
text = "abc";
you are changing the copy, not the one back in main
.
Also, you cannot in general assign strings in C - you have to use library functions like strcpy()
instead. To make your code work, you need to change:
text = "abc";
to:
strcpy( text, "abc" );
You can't just printf("text in main : %s\n",text);
it has no meaning in C, you either can use a function like strcpy()
that takes each char and organize them to be a String ! or a regular for loop and run it all over the array and print organs without space.
int i;
for (i=0 ; i<strlength(text);i++)
{
printf ("%d",text[i]);
}
精彩评论