I am trying to learn C 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 flawlessly if size <= 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);
}
size, sincedata[size - 1]` is always an out-of-bounds error, since the array is always one element shorter.sizeis signed and may well be negative, and that you don't allocate any memory for the bulk of the array elements.)