iphoneQ:
Reading char in string
I have a char array like this:
char* a;
char* b = "w";
char* c = "w";
a = b;
a[0] = c[0];
c[0] = 'h';
After this I have printed a and b the result is:
w
wh
I need to print the result like this:
How can I do this?
A:
There's two problems with your code:
This is not a valid definition of a pointer to a char. It should be
char * a;
The next line is invalid as well. You cannot assign a pointer to a char in C.
You can assign it to a character.
int main()
{
char * a = "w";
char * b = "w";
char * c = "w";
a[0] = c[0];
c[0] = 'h';
printf("a = %s, b = %s, c = %s
", a, b, c);
return 0;
}
You could make this work if you wanted to, but I would not recommend it.
And to answer your question, you need to print a, then b, then c. There's no magic trick here.
char* a = "w";
printf("a = %s, b = %s, c = %s
The printf() function expects a pointer to a char (what you gave it). Then it tries to printf() the char, which isn't valid.
printf("%s
", a);
This solution is better, because now you don't have to use array syntax, but strcpy() function.
char a[100];
char b[100];
char c[100];
strcpy(a, "w");
strcpy
Related links:
Comments