0

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);
}
Moe
  • 17
  • 7
  • For an 'int' data type (like your `trail` member), `NULL` is the same as zero. So your test/set is really doing: `if (x == 0) x = 0;`. See the problem, now? Further, unless *explicitly* initialized, the data members will have undefined values (seemingly random). – Adrian Mole May 11 '21 at 09:39
  • Since the array is rectangular, why don't you just allocate a single block of memory for the entire array? – lulle2007200 May 11 '21 at 09:48
  • @lulle Im not sure how can you provide me with a link or something that can help? – Moe May 11 '21 at 09:52
  • [Correctly allocating multi-dimensional arrays](https://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays) – Lundin May 11 '21 at 09:53

1 Answers1

0

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335