结构中的数组malloc作为参数传递

时间:2014-08-27 13:36:42

标签: c arrays struct malloc

我想为一个需要使用的结构的成员的数组分配内存,在一个以struct为参数的函数中。

arg->A.size=(int*) malloc(N*sizeof(int));

将无法编译(请求成员'size'不是结构。

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;
}

3 个答案:

答案 0 :(得分:1)

您根本没有为struct A *A分配内存。在为A->size分配任何内容之前,您首先需要执行类似

的操作
B->A = malloc(sizeof(struct A));

答案 1 :(得分:1)

第二种情况是正确的,但崩溃是因为在main中声明的B内部的A尚未赋值。你可能想要像

这样的东西
struct A A;
struct B B;
B.A = &A;

function_AB(&B);

答案 2 :(得分:0)

如果在另一个结构中有结构指针,首先需要为其分配内存。然后为结构成员分配内存!

struct B {
    int tag;
    struct A* A;
};

此处A是指向名为A的结构的指针。首先为此分配内存,然后为struct A

的元素分配内存
arg->A = malloc(sizeof(struct A));

然后做 -

arg->A->size = malloc(N*sizeof(int));

int function_AB(struct B* arg) -

中尝试以下更改
int function_AB(struct B* arg){
int N=10;
arg->tag=99;
printf("tag assigned = %d \n", arg->tag);

arg->A = malloc(sizeof(struct A)); // First allocate the memory for struct A* A; 

arg->A->size = malloc(N*sizeof(int)); // Allocate the memory for struct A members
arg->A->val = malloc(N*sizeof(double));

// do your stuff

// free the allocated memories here
free(arg->A->size);
free(arg->A->val);
free(arg->A);

return 0;
}

不要投射malloc()的结果!

相关问题