【发布时间】:2014-08-27 23:09:59
【问题描述】:
我想为数组分配内存,这些数组是我需要使用的结构的成员,在一个将结构作为参数的函数中。
arg->A.size=(int*) malloc(N*sizeof(int));
不会编译(对成员“大小”的请求不是结构。
arg->A->size=(int*) malloc(N*sizeof(int));
会抛出分段错误错误
任何帮助将不胜感激。 这是代码,谢谢:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// struct A
struct A {
int dim; // dimensions
int* size; // points per dim array
double* val; // values stored in array
int total; // pow(size,dim)
};
// struct B that uses A
struct B {
int tag;
struct A* A;
};
int function_AB(struct B* B);
int main(void){
struct B B;
function_AB(&B);
return 0;
}
int function_AB(struct B* arg){
int N=10;
arg->tag=99;
printf("tag assigned = %d \n", arg->tag);
arg->A->size=(int*) malloc(N*sizeof(int));
return 0;
}
【问题讨论】: