Reputation: 1000
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:
abc
function is not the same?scanf
in the abc
function and it works! there are the same. Why?Upvotes: 3
Views: 186
Reputation: 1546
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]);
}
Upvotes: -3
Reputation:
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" );
Upvotes: 13