-1

I'm hiding a pointer with the typedef and I'm trying to make an array of it. my structure is:

typedef struct s {
    int y;
    int x;
    int value;
} s;

typedef s *t;

and the main:

int main()
{
    t *var;
    int arg;
    var = malloc(sizeof(t*));
    arg = 40;
    for (int x = 0; x < arg; x++)
    {
        var[x] = malloc(sizeof(t));
        var[x]->x = -1;
        var[x]->y = -1;
        var[x]->value = 0;
    }
    for (int x = 0; x < arg; x++)
    {
        printf("|%d| ",var[x]->value);
    }
    return 0;
}

sometime it just goes to segmentation fault and sometimes the value is just dirty, but it still means that it did not allocated the memory as intented. what am I missing? I'm just trying to make an array of type t with arg length which must be a variable

MarcoA7
  • 91
  • 5
  • 5
    *I'm hiding a pointer with the typedef*. Advice: Don't do that. It just obscures the code and makes it harder for everyone to understand. That may even be contributing to your current problem. The first `malloc` should use `sizeof(t * arg)` or better still `sizeof(*var * arg)`. And move `arg=40` to be above that. – kaylum Feb 03 '21 at 03:54

1 Answers1

0

I'm hiding a pointer with the typedef

This very bad practice is the root of all your bugs. Simply don't hide pointers behind typedef.

Because now you have a t* var which is actually a s**. Then you call var = malloc(sizeof(t*)); which is completely wrong, because you allocate room for a s**.

You should have allocated room for 40 * sizeof(s*) or otherwise var[x] will seg fault.

And then typedef or not, this is not a 2D array but a segmented look-up table, which adds extra complexity and slower code, for absolutely nothing gained. See Correctly allocating multi-dimensional arrays. But it doesn't even look like you need a 2D array, so what's all of that coming from?

With all of this in mind, lets go with the KISS principle and rewrite the code from scratch:

#include <stdio.h>
#include <stdlib.h>

typedef struct {
  int y;
  int x;
  int value;
} s;

int main (void)
{
  int arg = 40;
  s* var = malloc(arg * sizeof(*var));

  for (int i = 0; i < arg; i++)
  {
    var[i].x = -1;
    var[i].y = -1;
    var[i].value = 0;
  }
  for (int i = 0; i < arg; i++)
  {
    printf("|%d| ",var[i].value);
  }

  free(var);
  return 0;
}

A 2D version would use s (*var)[y] = malloc( sizeof(s[x][y]) ); instead.

Lundin
  • 195,001
  • 40
  • 254
  • 396