String C is true in one function and flushes garbage in another

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 it is deduced.

text in abc function : abc
text in main : ฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬ๑ป ๚

My questions:

  • Why is the text variable in the main function and in the function abcnot the same?
  • I am trying to change the use of scanfa function abcand it works! have the same thing. Why?
  • How to change the code to make it work. I mean question 1, which makes the main function the same in the abc function?
+3
source share
2 answers

When you call the function:

 abc(text);

a copy of the pointer is created text, and this pointer is used in the function abc(). So when you say:

text = "abc";

you change the copy, not back to main.

, C - , strcpy(). , :

 text = "abc";

 strcpy( text, "abc" );
+13

printf("text in main : %s\n",text); C, strcpy(), char ! , .

int i;
for (i=0 ; i<strlength(text);i++)
{
    printf ("%d",text[i]);
}
-3

All Articles