简体   繁体   中英

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.

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 (!((*(arr+i)+j)->trail))

does not make a sense because uninitialized objects have indeterminate values and the function malloc does not initialize allocated memory.

You could use for example calloc instead of malloc in this loop

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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