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
abcfunction is not the same? - I try to change to use
scanfin theabcfunction 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:
a copy of the pointer
textis made, and this pointer is the one used in the functionabc(). So that when you say: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:to: