Reputation: 137
My code is working with integer's value, but when I tried to add the character value ,then I have error.
Here's my code:
1 #include <stdio.h>
2
3 struct _pointer{
4
5 int x;
6 int y;
7 char Q[200];
8
9 }address,*pointer;
10
11
12 main()
13 {
14 pointer = &address; // here we give the pointer the address.
15 pointer->x = 10; // here we give the pointer the value to variable x.
16 pointer->y = 30; // here we give the pointer the value to variable y.
17 (*pointer).Q = "BANGO!";
18 printf("The x variable is %d\nThe y variable is %d\nTheText\n",pointer-> x,pointer->y,pointer->Q);
19
20 }
21
So where is my mistake ?
Thanks
Upvotes: 0
Views: 135
Reputation: 1890
You're passing pointer->Q
to printf
but there is no %s
in the format string.
And also you should copy string with strcpy(pointer->Q, "mystring");
Upvotes: 2
Reputation: 44838
To my mind, you didn't even try to compile your code.
First of all, you cannot just assign a string to char[]
you need to use strcpy(char *to, char *from);
.
Then, you have three arguments to printf
but only two formatting %
's.
Correct way:
printf("The x variable is %d\nThe y variable is %d\nTheText variable is %s\n",pointer->x,pointer->y,pointer->Q);
and
strcpy(pointer->Q,"Your text");
Upvotes: 1
Reputation: 19864
I would suggest to use
strlcpy(pointer->Q,"BANGO!",sizeof(pointer->Q));
which is less error prone and guarantees a null termination of your string.
Upvotes: 0
Reputation: 53006
I can see a few errors, the most important one is that you can't assign to arrays in c, to set the contents of the array to those of the string you need to copy the contents, you can use strcpy()
for that, in your case you need
strcpy((*pointer).Q, "BANGO!");
also, the rest of your code doesn't seem to be a good Idea, I recommend this instead
#include <stdio.h>
#include <string.h>
struct MyStruct
{
int x;
int y;
char Q[200];
};
int
main()
{
struct MyStruct instance;
struct MyStruct *pointer;
pointer = &instance;
pointer->x = 10; // here we give the pointer the value to variable x.
pointer->y = 30; // here we give the pointer the value to variable y.
/* copy the contents of "BANGO!" into the array Q */
strcpy(pointer->Q, "BANGO!");
printf("x = %d\ny = %d\nQ = %s\n", pointer->x, pointer->y, pointer->Q);
/* ^ you need this for ---------------^ this */
/* or even */
printf("x = %d\ny = %d\nQ = %s\n", instance.x, instance.y, instance.Q);
/* which will print the same, since you modified it through the pointer */
return 0;
}
you should also note, that main()
returns and int
.
There is no good reason to use global variables in a general case, there are situations where they are needed or useful, but in general you should avoid them.
Upvotes: 1
Reputation: 2711
copying a string is done by strcpy(char *dst, const char *src)
Copy the string like this
strcpy(pointer->Q,"BANGO!");
Upvotes: 2