【发布时间】:2021-03-28 11:04:47
【问题描述】:
// Trying to create 2D array dynamically using pointers
#include <stdio.h>
#include <malloc.h>
int main()
{
int *pool, **pool2, r = 3, c = 4; /* r and c corresponds to rows and columns respectively */
pool = (int *)calloc((r * c), sizeof(int)); /* creating all the blocks of int of 2D array*/
pool2 = (int **)calloc(r, sizeof(int *)); /* using double pointers same as the number of rows with a thought of storing base addresses of each row*/
int count = 0;
for (int k = 0; k <= (r - 1); k++)
{
pool2[k][0] = &pool[count]; /* my query here : Since pool is of (int *) type, pool2 (being a double pointer) should be able to store the address of pool.*/
// pool2[k] = &pool[count]; /* <------ BUT This WORKS FINE (after un-commenting)... instead of the above line !! */
for (int m = 0; m <= (c - 1); m++)
{
printf("pool2[%d][%d] = %d\n", k, m, pool2[k][m]);
}
count += c; /* count increases to give the address of first block of the row (using &pool[count])*/
}
free(pool);
free(pool2);
return 0;
}
输出:
warning: assignment makes integer from pointer without a cast [-Wint-conversion]
pool2[k][0] = &pool[count];
为什么双指针(pool2)不能存储'pointer to int'的地址。
【问题讨论】:
-
你读过代码中的cmets吗??我没有要求调试我的代码,输出警告只是为了给出一个想法。当然,我搜索了该警告消息并尝试阅读与之相关的其他主题和问题。我在这里问了一个具体的事情,我可能会错过这个概念。这就是为什么我专门创建一个帐户只是为了问这个问题。这是我在这个网站上的第一个问题,也许我的方式是错误的.. 但至少试着首先了解实际询问的内容。谢谢你的评论。
标签: arrays c pointers 2d variable-assignment