如何为value1 [i] - > value2添加价值?

时间:2016-12-27 14:40:04

标签: c pointers matrix

这适用于C语言和ubuntu。

我目前陷入了这个问题:

struct dretva {
    int id;
    int p;  
    int prio; 
    int rasp; 
};

struct dretva *P[5];

int nove[6][5] =
{
    { 1,  3, 5, 3, 1 },
    { 3,  5, 6, 5, 1 },
    { 7,  2, 3, 5, 0 },
    { 12, 1, 5, 3, 0 },
    { 20, 6, 3, 6, 1 },
    { 20, 7, 4, 7, 1 },
};

我如何为P增加价值? 我是这样做的:

P[0]->id=nove[0][2];

但是当我用printf这样写它时:

printf("%d",P[0]->id);

它表示Segmention fault(核心转储),这意味着P [0] - > id没有值。怎么样?如何为P [0] - > id?

添加值

谢谢。

2 个答案:

答案 0 :(得分:3)

为这些结构指针分配内存后,您可以添加添加或提及的方式。

如果你使用指针,你需要给它一些内存,你可以指向...

现在你因此而得到错误..(没有分配内存) 添加此行并使用值启动它们。

for(int i=0;i<5;i++)
  P[i]=malloc(sizeof(struct dretva));

4386427指出的简单方法

struct dretva *P = malloc(5 * sizeof(struct drevta)); 
if (P == NULL) {
    exit(1);
}

以后释放记忆的好习惯。

答案 1 :(得分:1)

分配struct而非指向struct的指针,如下所示:

struct dretva P[5];
//            ^
//     no asterisk
P[0].id=nove[0][2];
//  ^
//  dot in place of ->

目前,您分配的指针未设置为指向实际的struct,因此读取或写入指针是未定义的行为。

相关问题