1

I have a stract and there should be an array whose size I don't know yet in main I try. Here, for example, I created a define N, but in fact, I accept different data in different ways, including the array W. I have to allocate memory for my array arr of structs.

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

#define N 10

struct vector {
    int size;
    int *arr;
    int length;
};

void main(void) {  
    int w[N] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    struct vector *ptr;
    ptr->arr = (int *)malloc(sizeof(int) * N);
    if (ptr->arr == NULL) 
        printf("Unable to allocate memory :(\n");

    for (int i = 0; i < N; i++) {
        ptr->arr[i] = w[i];
        printf("%d ", ptr->arr[i]);
    }
    printf("\n");
}

Tried to do it in different ways but nothing works. gives an error in the terminal: Segmentation fault (core dumped). please help me

Yael
  • 93
  • 7

1 Answers1

2

you need to allocate the ptr first with your structure type. right now ptr=Null, and you need it to point to a memory location with the size of your structure before you can allocate ptr->arr.

try this:

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

#define N 10

typedef struct vector {
   int size;
   int *arr;
   int length;
}vector_t;

void main(void)
{  
    int w[N]={1,2,3,4,5,6,7,8,9};
    vector_t *ptr=(vector_t *)malloc(sizeof(vector_t));

    ptr->arr=(int *) malloc( sizeof(int)*N );
    /* ---- the rest of your code--- */
    free(ptr->arr);
    free(ptr);


}
Sara Awwad
  • 40
  • 6
  • @Sara Awwad thank you for responding to help, I did a little differently – Yael Jun 29 '22 at 13:09
  • no problem :) I had a typo in my code and @chqrlie pointed it out I just edited it – Sara Awwad Jun 29 '22 at 13:11
  • `struct vector ptr[1];` instead of `vector_t *ptr=(vector_t *)malloc(sizeof(vector_t));` also good? – Yael Jun 29 '22 at 13:14
  • @Yael: Yes, it works. One could also write `struct vector ptr__[1], *ptr = &ptr__;` Indeed `ptr->arr = ...` is equivalent to `ptr[0].arr = ...` – chqrlie Jun 29 '22 at 13:21
  • 1
    @Yael: your code uses a `vector` object allocated with automatic storage (aka *on the stack*), whereas @SaraAwwad allocates the `vector` object from the heap, just like the array of `int` it points to. – chqrlie Jun 29 '22 at 13:23
  • when you use struct vector ptr[1]; you are not using pointers anymore, instead you are consuming space on the stack. when you allocate memory, you would be using the heap instead, which allows you to deal with large structures. in the end, it depends on what you want to do with your structure and how big your array is, but in my opinion, using pointers is more elegant in this case. ps: don't forget to deallocate them in the end of the code – Sara Awwad Jun 29 '22 at 13:28