简体   繁体   English

如何检查动态分配的二维数组的元素是否是 C 中的 NULL

[英]how to check if elements of a dynamically allocate 2d array are NULL in C

I have a dynamically allocate 2d array pointing to a structure.我有一个指向结构的动态分配二维数组。 I'm trying to fill the NULL values of the array with the number 0. There are no errors or warnings it's just printing some random values.我正在尝试用数字 0 填充数组的 NULL 值。没有错误或警告,它只是打印一些随机值。

This is a simplified version of the code:这是代码的简化版本:

#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 starters this loop对于初学者这个循环

for (int i=0; i<cols; i++)
              ^^^^^^^
     arr[i] = (struct Data*)malloc(cols * sizeof(struct Data));

is incorrect.是不正确的。 It seems you mean看来你的意思

for (int i=0; i<rows; i++)
              ^^^^^^^
     arr[i] = (struct Data*)malloc(cols * sizeof(struct Data));

This if statement这个 if 语句

if (!((*(arr+i)+j)->trail))

does not make a sense because uninitialized objects have indeterminate values and the function malloc does not initialize allocated memory.没有意义,因为未初始化的对象具有不确定的值,并且 function malloc 不会初始化分配的 memory。

You could use for example calloc instead of malloc in this loop您可以在此循环中使用例如calloc而不是malloc

for (int i=0; i<rows; i++)
     arr[i] = (struct Data*)calloc(cols, sizeof( struct Data ));

Pay attention to that apart from this call of free除了这个免费的电话外,请注意

free(arr);

you need also to free all allocated sub-arrays in a loop.您还需要在循环中释放所有分配的子数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM