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:

  1. parse user input: produce either valid size_t integer or abort. check value neither 0 nor large, or abort.

  2. suppose you've parsed value n. allocate memory n copies of structure:

    dados * data = malloc(n * sizeof(dados)); 

    at end, release memory:

    free(data); 
  3. use proper parsing error handling populate each array member data[i].

  4. practice file operations separately.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -