不行,不過下面的寫法也許可以達成你想要的效果,提供給您參考參考
#include<stdio.h>
struct aaa {
int value;
};
struct aaa *num[9];
int main(void) {
num[0] = malloc(sizeof(struct aaa));
num[0]->value = 1234;
printf("%d", num[0]->value);
return 0;
}
我猜你想要的效果是這樣:
#include "stdio.h"
#include "stdlib.h"
struct aaa{
int b;
}* num[9];
int main() {
for (int i = 0; i < sizeof(num) / sizeof(struct aaa *); i++) {
num[i] = (struct aaa *) malloc(sizeof(struct aaa));
if (num[i]) {
num[i]->b = i;
printf("%d\n", num[i]->b);
}
}
}
雖然我可能沒真的很懂 C,但我這樣寫沒問題耶?
#include "stdio.h"
#include "stdlib.h"
int main() {
/* 在 initialize struct 的時候宣告變數 */
/* 也許 C 把 struct 寫在外面才是常規嗎? */
struct aaa {
int b;
} *num[9];
for (int i = 0; i < 9; i++) {
num[i] = (struct aaa *)
malloc(sizeof(struct aaa *));
if (num[i]) {
num[i] -> b = 2 * i;
printf("The b of %d is %2d.\n",
i, num[i] -> b);
}
else {
fprintf(stderr, "ERROR on memory");
fprintf(stderr, " allocation of");
fprintf(stderr, " the %dth item!...", i);
return 1;
}
}
for (int i = 0; i < 9; i++) free(num[i]);
return 0;
}