Working in c. I am trying to dynamically allocate an array that is within a struct. The array will hold rows of char data. I can't see any errors, any help is appreciated.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct data
{
char **d;
}Data;
int main(void)
{
Data *a = malloc(10*sizeof(Data));
int i = 0, length = 0;
for(i = 0; i < 10; i++)
{
char buffer[1000] = { '\0' };
printf("\nenter data\n");
fgets(buffer, 1000, stdin);
length = strlen(buffer);
a[i].d[i] = malloc(sizeof(length+1)); //errors here, unhandled exception
strcpy(a[i].d[i], buffer);
}
for (i = 0; i < 10; i++)
{
printf("%s", a[i].d[i]);
}
return 0;
}
Data.dat indexi, d must be allocd to have defined behaviour. so first you alloc thechar **and then alloc yourchar *..