Tuesday, 13 August 2013

Dynamic Memory Allocation with pointer arrays

Dynamic Memory Allocation with pointer arrays

I am trying to learn C language from tutorials on the web, and I came up
with this simple code to try and understand memory allocation on pointers
and arrays.
The code compiles and runs flawless if size is <=2, but if size >2 it
gives a segmentation error. Can someone please shed a light on how to do
this 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 do 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);
}
//////////////////////////////////////////////////////////////////////////////////////

No comments:

Post a Comment