在不同函数的动态分配整数阵列上的segfault
#include <stdio.h>
#include <stdlib.h>
void a(int** parr) {
*parr = malloc(sizeof(int) * 5);
}
void b(int** parr) {
*parr[0] = 100;
*parr[1] = 200;
}
int main(void) {
int* parr;
a(&parr);
parr[0] = 50;
parr[1] = 75;
b(&parr);
printf("%d %d\n", parr[0], parr[1]);
return 0;
}
由于某种原因,此segfault在上*Parr [1] = 200
,我不知道原因。我将数组的整数指针传递到b()
,*parr [0] = 100
按预期工作。
#include <stdio.h>
#include <stdlib.h>
void a(int** parr) {
*parr = malloc(sizeof(int) * 5);
}
void b(int** parr) {
*parr[0] = 100;
*parr[1] = 200;
}
int main(void) {
int* parr;
a(&parr);
parr[0] = 50;
parr[1] = 75;
b(&parr);
printf("%d %d\n", parr[0], parr[1]);
return 0;
}
For some reason, this segfaults on *parr[1] = 200
and I can't figure out why. I'm passing in an integer pointer to the array into b()
, and *parr[0] = 100
works as intended.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
[]
操作员的优先级高于Dereference*
运算符。因此,这两行代码需要参与括号的服务以获取所需的操作顺序:此外,实际上没有理由
b
函数进行双重指针,因为它不会改变原始parr
指针(与A
函数相比)。因此,代码可能更简单而更少的错误写为:并与:
The
[]
operator has higher precedence than the dereference*
operator. So those two lines of code need to engage the services of parenthesis to get the desired order of operations:Also, there is really no reason for the
b
function to take a double pointer as it does not change the originalparr
pointer (compared toa
function which does). So the code could be more simply and less error pronely written as:And called with: