[英]Allocation isn't working properly
I'm trying to put values in an array by sending the pointer address to a function and create dynamic allocation in the function itself. 我正在尝试通过将指针地址发送到函数并将值放置在数组中,并在函数本身中创建动态分配。 after the allocation, I get the first value in the first index. 分配后,我在第一个索引中得到了第一个值。
This is the error message that for the problem: Unhandled exception at 0x00941589 in ConsoleApplication1.exe: 0xC0000005: Access violation writing location 0xCCCCCCCC. 这是针对该问题的错误消息:ConsoleApplication1.exe中0x00941589的未处理异常:0xC0000005:访问冲突写入位置0xCCCCCCCC。
This is what I have done: 这是我所做的:
void mamain()
{
*A = NULL;
func(&A);
}
void func(int** A)
{
*A = (int*)malloc(sizeof(int) * 5);
*A[0] = 5;
*A[1] = 8;
*A[2] = 67;
*A[3] = 2;
*A[4] = 3;
for (int i = 0; i < 5; i++)
{
printf("%d,", *A[i]);
}
}
I don't understand why my code isn't working, trying to figure it out but no success. 我不明白为什么我的代码无法正常工作,试图弄清楚但没有成功。
You've assigned the result of your malloc
call to *A
, not A
; 您已将malloc
调用的结果分配给*A
,而不是A
; thus, the expression *A
is your array. 因此, 表达式 *A
是您的数组。 Since []
has higher precedence than unary *
, the expression *A[0]
is parsed as *(A[0])
; 由于[]
优先级高于一元*
,因此表达式*A[0]
被解析为*(A[0])
; this isn't what you want. 这不是你想要的。
You'll need to explicitly group the *
operator with A
before doing the subscript: 在执行下标之前,您需要将*
运算符与A
明确组合在一起:
(*A)[0] = 5;
(*A)[1] = 8;
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.