Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

c - 将指针值传递给c中的结构(pass pointer value into a struct in c)

What is wrong with the following code?

(以下代码有什么问题?)

It generates a Segmentation fault.

(它将生成分段错误。)

#include <stdio.h>
#include <stdlib.h>

typedef struct{
    int ** access;
}item;

int main()
{

    int access[5][5];

    for(int i = 0; i < 5; i++){
        for(int j = 0; j<5; j++){
            access[i][j] = 5;
        }
    }

    item * p = malloc(sizeof(item));
    p->access = access;

    for(int i = 0; i < 5; i++){
        for(int j = 0; j<5; j++){
            printf("%d",p->access[i][j]);
        }
    }


    return 0;
}

I want to create a struct that contains the value of a double array created in the main function.

(我想创建一个包含在main函数中创建的double数组的值的结构。)

What is wrong with it?

(怎么了)

  ask by Billy translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can have array of pointer in your struct like int *[5].

(您可以在结构体中使用int * [5]之类的指针数组。)

But you have to assign address of each row in 2D array to struct data member.

(但是您必须在2D数组中分配每行的地址以构造数据成员。)

Also free your memory allocated in malloc.

(同时释放在malloc中分配的内存。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...