typedef struct line {
int a;
int b;
} line;
int main() {
line *v;
int c, d, j;
char a;
int i;
scanf("%d", &n)
for (i = 0; i < n; i++) {
scanf("%c", &a);
v = (line*) malloc(n * sizeof(line));
if (a == '+') {
scanf("%d %d", &v[j]->a, &v[j]->b);
}
}
I want to make an array that holds a struct info, and then use that info in my function . But I am getting some errors and I don't know if I used well the pointer.
I have tried with v[j].a but it didn't work. (I used this because I am more familiar from linked-list.)
2 Answers 2
Use &(v[j].a) instead, which is equal to &((v+j)->a). The name of an array is a pointer to the first element. So v[j] is an element of type struct line. In order to get one of its fields you use .a.
Also, check your code for some other errors because some variebles are not initialized.
2 Comments
&(v[j].a) == &v[j].a. In this program OP allocates the array of the structs not the array to the structs.First of all you malloc a new memory on every iteration and the previous one becomes unavailable.
Abstracting from the logic of the program
typedef struct line {
int a;
int b;
} line;
int main(void) {
line *v;
int c, d, j;
char a;
int i,n;
scanf("%d", &n);
v = malloc(n * sizeof(line));
if(v == NULL) return -1;
for (i = 0; i < n; i++) {
scanf("%c", &a);
if (a == '+') {
scanf("%d %d", &v[j].a, &v[j].b);
}
}
}
2 Comments
scanf("%c", &a); --> Hmmm. Likely a will get the value of '\n'.
n. Suggest posting compilable code.scanf("%c", &a);-->scanf(" %c", &a);(Add space).scanf("%d", &n)This statement is missing the trailing;The posted code does not compile! amongst other things it is missing the#includestatement forstdio.h