#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.
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
You misspelled typedef
. Otherwise, it should work. Other criticisms:
malloc()
?ptr + i == &arr[i]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.