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
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);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments