Reputation: 5
I have initialized the array for one of the element in the structure, there were some errors in printing the output, please point the errors and guide in solving it . Thanks!
#include<stdio.h>
typedef struct person
{
int row[3];
int age;
}PERSON;
int main()
{
int i;
PERSON p;
PERSON *pptr=&p;
pptr->row[3] = {4,5,6};
for (i = 0; i < 3; i++) {
printf (" %d\n", pptr->row[i]);
}
return 0;
}
Upvotes: 0
Views: 163
Reputation: 320729
Array objects in C language are not assignable. You cannot set the values in the entire array by using assignment. So, to do what you are trying to do using assignment syntax is impossible.
You had a chance to initialize your array at the point of declaration, i.e. when you defined object p
PERSON p = { { 4, 5, 6 } };
but you did not use that chance. After that it is too late to do it using pure core language features.
To set the values in the entire array after the point of declaration you can use a library function, like memcpy
, in combination with a compound literal
memcpy(pptr->row, (int []) {4, 5, 6}, sizeof pptr->row);
Upvotes: 1
Reputation: 9234
When you have done PERSON p;
. object p
is created containing indeterminate values
.
It means all the data members are already initialized with garbage since it's on stack.
So, pptr->row[3] = {4,5,6};
is not the initialization of the array an not allowed in this case. The for
loop method is the best in this case.
for (i = 0; i < 3; i++)
scanf("%d",&(pptr->row[i])); // prenthrsis is for human readability
Upvotes: 0
Reputation: 1601
#include<stdio.h>
typedef struct person
{
int row[3];
int age;
}PERSON;
int main()
{
int i;
PERSON p;
PERSON *pptr=&p;
pptr->row[0] = 4;
pptr->row[1] = 5;
pptr->row[2] = 6;
for (i = 0; i < 3; i++) {
printf (" %d\n", pptr->row[i]);
}
return 0;
}
You can't initialize array like this pptr->row[3] = {4,5,6};
, You can use the above method or use for
loop to initialize array..
Upvotes: 0
Reputation: 18368
You can't assign values to array like this: pptr->row[3] = {4,5,6};
. Such syntax is valid only at initialization. You need to set each value manually or initialize your array with the values you want, something like this: PERSON p = {{4,5,6}, 0};
.
Upvotes: 0