#include<stdio.h>
#include <stdlib.h>
typedf struct
{
int a;
int b;
} STR;
int main(void)
{
STR *arr[4];
STR **ptr=arr;
for(int i=0; i<4; i )
{
arr[i]=(STR*)malloc(sizeof(STR));
(*arr[i]).a=i 7;
(**(ptr i)).b=i 3;
}
printf("%d\n", ptr[2]->a);
printf("%d", (*(arr 3))->b);
return 0;
}
How can I make the correct code and it can compile, also I want to know what is wrong at my code.
CodePudding user response:
Apart from the misspelled typedef
and that it leaks memory, it's not wrong. It's however doing the dereferencing in overly complex ways.
Suggested simplifications and notes:
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#define Size(x) (sizeof (x) / sizeof *(x)) // to not have to hardcode `4` in the loops
typedef struct {
int a;
int b;
} STR;
int main(void) {
STR *arr[4];
STR **ptr = arr; // same as: &arr[0];
for (size_t i = 0; i < Size(arr); i ) { // use the helper macro
arr[i] = malloc(sizeof *arr[i]); // same as: sizeof(STR)
arr[i]->a = i 7; // simpler dereferencing
ptr[i]->b = i 3; // simpler dereferencing
}
printf("%d\n", ptr[2]->a); // simpler dereferencing
printf("%d\n", arr[3]->b); // simpler dereferencing
// and finally, free the allocated memory:
for (size_t i = 0; i < Size(arr); i ) { // use the helper macro again
free(arr[i]);
}
}
Output:
9
6
CodePudding user response:
You misspelled typedef
. Otherwise, it should work. Other criticisms:
- Why are you casting the return value of
malloc()
? ptr i == &arr[i]
- If your compiler doesn't support C99, you'll need to remove the initial declaration from the for loop.