Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 将指向数组的指针传递给函数_C_Pointers - Fatal编程技术网

C 将指向数组的指针传递给函数

C 将指向数组的指针传递给函数,c,pointers,C,Pointers,我试图修改函数中数组的元素。这在main中可以正常工作,但当我将它移植到函数时,它会在访问数组的第一个成员后出现故障 下面的代码只是我的实际代码的简化版本,以显示我在哪里得到了错误 #include <stdio.h> #include <stdlib.h> typedef struct { unsigned short id; } voter; void initialise(voter** votersPtr, unsigned short *numOfV

我试图修改函数中数组的元素。这在main中可以正常工作,但当我将它移植到函数时,它会在访问数组的第一个成员后出现故障

下面的代码只是我的实际代码的简化版本,以显示我在哪里得到了错误

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

typedef struct {
    unsigned short id;
} voter;

void initialise(voter** votersPtr, unsigned short *numOfVoters) {
    *votersPtr = malloc(sizeof(voter)*(*numOfVoters));

    for(int i = 0; i < *numOfVoters; i++) {
        votersPtr[i]->id = (unsigned short) i;
        printf("%hu \n", votersPtr[i]->id);
    }
}

int main(void) {
    unsigned short numOfVoters = 480;
    voter* voters = NULL;

    initialise(&voters, &numOfVoters);

    return EXIT_SUCCESS;
}
#包括
#包括
类型定义结构{
无符号短id;
}选民;
无效初始化(投票人**votersPtr,未签名短*投票人){
*votersPtr=malloc(sizeof(投票人)*(*numofvorters));
for(int i=0;i<*numo;i++){
votersPtr[i]->id=(无符号短)i;
printf(“%hu\n”,votersPtr[i]->id);
}
}
内部主(空){
无符号短NUM=480;
投票者*投票者=NULL;
草签(&选民,&投票人);
返回退出成功;
}

非常感谢您的帮助。

请记住,
votersPtr
是指向数组指针的指针

那么,下面这句话不应该是:

votersPtr[i]->id = (unsigned short) i;
取而代之的是:

(*votersPtr)[i].id = (unsigned short) i;

votersPtr[i]->id
,与
(*votersPtr[i])相同。id
应该是
(*votersPtr[i]。id

类型
投票者**
是指向
投票者
对象的指针数组,或者指向
投票者
对象数组的指针。您的代码将其用作第一个,但应将其用作第二个。改变

votersPtr[i]->id = ...


一切都会好起来的。

谢谢!实际上我已经试过了,但忘记在printf语句中更改它,导致segfault仍然出现。感谢您解释我为什么不能使用“->”,我现在理解了这个问题。避免这种错误的一种方法是使
初始化
函数以
选民*ptr=malloc…
开头,然后在结尾,do
*votersPtr=ptr。IMHO这使得代码更易于阅读,也意味着如果您必须在构建结果的过程中出于某种原因中止函数,那么调用方不会看到部分构建的结果。
(*votersPtr)[i].id = ...