[英]how to check if elements of a dynamically allocate 2d array are NULL in C
我有一个指向结构的动态分配二维数组。 我正在尝试用数字 0 填充数组的 NULL 值。没有错误或警告,它只是打印一些随机值。
这是代码的简化版本:
#include <stdio.h>
#include <stdlib.h>
int rows = 2, cols=3 ;
struct Data
{
int trail;
};
struct Data** WritingData()
{
//initializing 2d array
struct Data **arr = (struct Data**)malloc(rows * sizeof(struct Data*));
for (int i=0; i<cols; i++)
arr[i] = (struct Data*)malloc(cols * sizeof(struct Data));
//giving some values as an example
(*(arr+0)+0)->trail = 1;
(*(arr+1)+0)->trail = 1;
(*(arr+0)+1)->trail = 1;
//checking if value is NULL to replace with 0
for (int i = 0; i < rows ; i++) {
for (int j = 0; j < cols; j++){
if (!((*(arr+i)+j)->trail))
(*(arr+i)+j)->trail = 0;
else continue;
}
}
return(arr);
}
int main()
{
struct Data **arr = WritingData();
//printing result
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
{
printf(" %d ", (*(arr+i)+j)->trail);
}
printf("\n");
}
free(arr);
}
对于初学者这个循环
for (int i=0; i<cols; i++)
^^^^^^^
arr[i] = (struct Data*)malloc(cols * sizeof(struct Data));
是不正确的。 看来你的意思
for (int i=0; i<rows; i++)
^^^^^^^
arr[i] = (struct Data*)malloc(cols * sizeof(struct Data));
这个 if 语句
if (!((*(arr+i)+j)->trail))
没有意义,因为未初始化的对象具有不确定的值,并且 function malloc 不会初始化分配的 memory。
您可以在此循环中使用例如calloc
而不是malloc
for (int i=0; i<rows; i++)
arr[i] = (struct Data*)calloc(cols, sizeof( struct Data ));
除了这个免费的电话外,请注意
free(arr);
您还需要在循环中释放所有分配的子数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.