c - Dynamic Memory Allocation with pointer arrays -
i trying learn c tutorials on web, , came simple code try , understand memory allocation on pointers , arrays.
the code compiles , runs flawlessly if size
<= 2, if size
> 2 gives segmentation error. can please shed light on how properly?
thank you.
#include <stdio.h> #include <stdlib.h> int main () { int i, size; printf("quantos registos pretende inserir? "); scanf("%d",&size); getc(stdin); typedef struct { char nome[81]; int idade; char cargo[81]; } dados; dados *data[(size-1)]; data[(size-1)] = (dados *)malloc(sizeof(dados)); for(i=0;i<size;i++) { printf("\ninsira os dados funcionário: "); printf("\n\n\tnome: "); gets(data[i]->nome); printf("\n\tidade: "); scanf("%d",&data[i]->idade); getc(stdin); printf("\n\tcargo: "); gets(data[i]->cargo); file *fdados; if(!(fdados = fopen("dados.txt","a+"))) { printf("impossivel aceder ao ficheiro, verfique o erro ocorrido ..."); } fprintf(fdados, "funcionário %d:",(i+1)); fprintf(fdados, "\n\n\tnome: %s",data[i]->nome); fprintf(fdados, "\n\tidade: %d",data[i]->idade); fprintf(fdados, "\n\tcargo: %s\n\n",data[i]->cargo); fclose(fdados); } free(data[(size-1)]); fflush(stdin); return(0); }
you're giving way in 1 go. break problem down , test each component:
parse user input: produce either valid
size_t
integer or abort. check value neither 0 nor large, or abort.suppose you've parsed value
n
. allocate memoryn
copies of structure:dados * data = malloc(n * sizeof(dados));
at end, release memory:
free(data);
use proper parsing error handling populate each array member
data[i]
.practice file operations separately.
Comments
Post a Comment