我创建了一个简单的程序,在 c 中使用 INT 多维数组。
他的设计结构如下:
typedef struct s_control
{
int rangees;
int **rangees_content;
} t_control;
然后,我 malloc 结构等...... 但是,当我尝试编辑这样的案例时:
opt->rangees_content[line] = tmp;
其中“tmp”是由“int tmp;
”声明的 int
然后我编译并得到:
./main.c:9:30: warning: assignment makes pointer from integer without a cast [enabled by default] opt->rangees_content[line] = tmp;
有人有想法吗?
谢谢
最佳答案
您正在尝试将整数分配给 int
指针,这是不应该执行的,它会在尝试取消引用指针时导致未定义的行为。
换句话说,int **
意味着它可以像二维数组一样被访问,您正在访问其类型为 int *
的维度之一并尝试为其分配一个int
。
这是如何使用 int **
指针的示例
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct s_control
{
size_t rangees;
int **rangees_content;
} t_control;
int
main()
{
t_control control;
size_t rowSize;
/* this is irrelevant to your problem, just initialize the random seed */
srand(time(NULL));
/* Initialize the struct members */
control.rangees = 10;
control.rangees_content = malloc(control.rangees * sizeof(int *));
/* ^
* Above, you allocate 'control.rangees' pointers of 'int'
*/
if (control.rangees_content == NULL)
return -1;
rowSize = 10; /* this value can be changed */
for (size_t i = 0 ; i < control.rangees ; ++i)
{
/* this is the i-th row of the array and has type 'int *', malloc it */
control.rangees_content[i] = malloc(rowSize * sizeof(int));
if (control.rangees_content[i] == NULL)
{
/* always handle malloc failure */
while (i >= 0)
free(control.rangees_content[i--]);
free(control.rangees_content);
return -1;
}
/* Iterate through the array elements, and assign random values to them */
for (size_t j = 0 ; j < rowSize ; ++j)
control.rangees_content[i][j] = rand() % 100;
}
/* print and free the array */
for (size_t i = 0 ; i < control.rangees ; ++i)
{
for (size_t j = 0 ; j < rowSize ; ++j)
printf("%5d", control.rangees_content[i][j]);
printf("\n");
free(control.rangees_content[i]);
}
free(control.rangees_content);
return 0;
}
上面的程序,生成随机数并用它们填充数组,然后将它们输出到stdout
。
关于c - C 中 INT 的多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28658503/