0

My struct is

typedef struct {
unsigned int size ;
int * arr ;
} array_t ;

The function should initialize a struct with the length of a given number.

void init ( array_t * A, unsigned int size){
  A = malloc(sizeof(array_t));
  A->arr = calloc(size+1,sizeof(int));
  A->size = size;
  return;
}

But when I print the size of the struct in my main function I always get the wrong number. How do I assign the right value to size or what did I do wrong?

  • You cannot print the content of the allocated memory in `main` because you can't access it at all. What you assign to a parameter inside a funcion stays in that function. You only change a copy of your first parameter. – Gerhardh Feb 03 '21 at 08:32

2 Answers2

0

Your code is incorrect because it does not return the reference to the newly allocated memory:

void init ( array_t * A, unsigned int size){
  A = malloc(sizeof(array_t)); // <===== the allocated memory reference is lost
  A->arr = calloc(size+1,sizeof(int));
  A->size = size;
  return;
}

One way to fix it is to return the new array to the caller:

array_t * CreateArray (unsigned int size){
  array_t * A = malloc(sizeof(array_t));
  A->arr = calloc(size+1,sizeof(int));
  A->size = size;
  return A; /* return the new array */
}

Another way is to use a pointer but the caller need to do the malloc:

void init ( array_t * A, unsigned int size){
  A->arr = calloc(size+1,sizeof(int));
  A->size = size;
}

void main ()
{
  array_t Array;

  init(&Array);
}

Robert
  • 2,711
  • 7
  • 15
0

As @Robert mentioned, once you

...
A = malloc(sizeof(array_t));
...

You assign a new address to A, so all the initialization done afterwards is done on a memory address that you don't have any access to in your main function.

You actually don't need this line, you pass a pointer to an already allocated memory to the init functio. Just drop this line and it'll be fine.

YoavKlein
  • 2,005
  • 9
  • 38
  • That is probably not true. The purpose of that function seems to be the allocation of the memory. Therefore it is not safe to assume the pointer points to an existing object. IMHO it is more likely that a pointer is passed that does not point to an object. – Gerhardh Feb 03 '21 at 08:50
  • The pointer given to the function contains a memory address. You can't allocate memory in the same memory address pointed to by the pointer. If that space is not allocated, there's not much you can do about it. – YoavKlein Feb 03 '21 at 09:32
  • You can change the paramter to pointer to pointer as mentioned in the answer to the existing duplicate.Or you can return he new address via `return`. – Gerhardh Feb 03 '21 at 09:34