gpt4 book ai didi

c - 不确定我的关于 malloc (c) 的输出

转载 作者:行者123 更新时间:2023-11-30 19:38:51 24 4
gpt4 key购买 nike

在理解输出时我应该考虑什么?因为现在我的输出对于 20 个整数来说是垃圾,我不知道为什么。我的目标是创建 20 个数组,每个数组包含 30 个整数。所以最终的数组将包含 19 到 48 之间的整数。

#include <stdio.h>

#include <stdlib.h>

int main(int argc, char* argv[])
{

int **p;//Declaration of a pointer variable
int i = 0, j;
int rows = 20;
int columns = 30;

p = (int**)malloc(20 * sizeof(int)); //First "bookend" allocates space
printf("Hello World! I have created a dynamic 20-array of 20x30 integers!\n");

if (p == NULL)
{
printf("Failed to allocated memory!");
exit(1);
}



for (i = 0; i < 20; i++)
{
if (p[i] == NULL)
{
printf("Integers not allocated! ");
}
p[i] = (int**)malloc(20 * sizeof(int));
}


for (i = 0; i < 20; i++)
{
for (j = 0; j < 20; j++)
{
if (p[j] == NULL)
{
printf("Integers not allocated! ");
}
p[i][j] = (int *)malloc(40 * sizeof(int));

}
printf("%d\n", p[(i+1)+j]);
}

free(p);

return 0;
}

最佳答案

希望我的问题是正确的...

你得到的并不完全是垃圾......当你做p[i][j] = (int *)malloc(40 * sizeof(int));时,你只是在分配另一个包含 40 个元素的数组,并将其地址放入 p[i][j]... 因此,当您尝试打印 p[(i+1)+j] 您正在打印您分配的 40 个元素数组的地址。

关于c - 不确定我的关于 malloc (c) 的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37449521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com