简体   繁体   English

在C中更新结构数组失败

[英]Updating struct array fails in C

I'm looking for a simple solution to this. 我正在寻找一个简单的解决方案。 I only have one element and could easily turn it into a simple array of long integers but in the future I will have a struct of random data types so instead of me declaring a bunch of separate arrays of random types, I want to pack the data into a struct. 我只有一个元素,可以轻松地将其转换为长整数的简单数组,但是将来我将拥有随机数据类型的结构,因此,我不想打包一堆单独的随机类型数组,而是打包数据成一个结构。

In this code the problem lies with the calling of load() but I don't know how to solve it. 在这段代码中,问题出在load()的调用上,但我不知道如何解决。 When I use the & , in front of the struct variable, the compiler reports warning: passing argument 1 of 'load' from incompatible pointer type . 当我在结构变量前面使用& ,编译器会报告warning: passing argument 1 of 'load' from incompatible pointer type

The output I expect instead of errors or a segmentation fault is: 我期望的输出而不是错误或分段错误是:

0= 1
1= 11

What am I doing wrong? 我究竟做错了什么?

and here's the code: 这是代码:

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

typedef struct{
    long n;
}a;

void load(a** x){
    x[0]->n=1;
    x[1]->n=11;
}

int main(void){
    a** b=malloc(200);
    b[0]->n=2;
    b[1]->n=2;
    load(&b); //trouble starts here
    printf("0= %ld\n",b[0]->n);
    printf("1= %ld\n",b[1]->n);
    free(b);
    return 0;
}

You don't need pointer to pointers. 您不需要指向指针的指针。 Just use 只需使用

a* b=malloc(ELEMENTS * sizeof (a)); // essentially array with nr of ELEMENTS of type a

The function 功能

void load(a* x){
    x[0].n=1; // 0th structure object
    x[1].n=11; // 1th structure object .. you can access till ELEMENT-th index
}

You can call it like 你可以这样称呼它

load(b);  // you can directly pass the pointer

Anytime you run malloc , you need to check that it has not returned a NULL pointer (ptr == 0). 每次运行malloc ,都需要检查它是否未返回NULL指针(ptr == 0)。 If you try and access a NULL pointer, it can throw a segmentation fault. 如果尝试访问NULL指针,则可能引发分段错误。

One way to do this would be... 一种方法是...

a** b=malloc(200);
if(b != 0)
{
   //The rest of the code.
}

Thanks for the help, but I couldn't accept one answer because everyone solved portions of the problem. 感谢您的帮助,但我无法接受一个答案,因为每个人都解决了部分问题。

Here's what I came up with: 这是我想出的:

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

typedef struct{
    long n;
}a;

void load(a* x){
    x[0].n=1;
    x[1].n=11;
}

int main(void){
    a* b=calloc(1,sizeof(a)*100);
    if (!b){printf("memory error\n");return 1;}
    b[0].n=2;
    b[1].n=2;
    load(b);
    printf("0= %ld\n",b[0].n);
    printf("1= %ld\n",b[1].n);
    free(b);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM