开发者

C String is correct in one function and dumps garbage in the other

开发者 https://www.devze.com 2023-03-04 17:10 出处:网络
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);

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:

  1. Why is the text variable in the main function and in the abc function is not the same?
  2. I try to change to use scanf in the abc function and it works! there are the same. Why?
  3. 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]);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消