C:如何指向calloc数组?

标签 c memory-management calloc

我试图将指针指向一个 calloc 数组。出于某种原因,当我到达第二个元素时,程序强制退出。第一个元素打印出来并且工作正常。这是我的代码示例,只是试图通过第二个指针打印出所有元素:

integerArray = (int*)calloc(totalNum, sizeof(int));

if(integerArray == NULL)
{
    printf("ERROR! Number entered is invalid.");
    exit(1);
}

collectNumbers(totalNum, integerArray);

arrayAscending = &integerArray;
arrayDescending = &integerArray;

for(i = 0; i < totalNum; i++)
{
    printf("%3d", **(arrayAscending + i));
}

最佳答案

问题出在这里:

printf("%3d", **(arrayAscending + i));

您正在递增指向指针的指针。

根据我在这里看到的代码,应该是这样的:

printf("%3d", *((*arrayAscending) + i)));

首先,您应该取消引用 arrayAscending 以获得指针 integerArray 值,如果您不想使用索引,则仅在此之后递增它。

也可以这样写:

printf("%3d",(*ayyarAscending)[i]);

但实际上更简单的是使用索引:

printf("%3d", integerArray[i]);

关于C:如何指向calloc数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16207399/

相关文章:

c - Malloc、Calloc 用于测试我的内存极限

c - 二维数组动态内存分配崩溃

c - 'send' 的 OS X 冲突类型

c - 服务器未通过 GTK+ 中的客户端 GUI 接收到文本消息

c - 是什么原因导致错误 "undefined reference to (some function)"?

algorithm - 内存管理算法用在哪里?

arrays - MATLAB:确定结构数组的总长度/大小,其中字段作为结构数组

c - 如何从不兼容的指针类型中删除错误 "passing argument 1 of ‘gtk_entry_get_buffer’”

iphone - 使用仪器进行内存分析

c - malloc、calloc 和动态数组