Search code examples
csegmentation-faultdynamic-memory-allocation

How to use `malloc/calloc` inside a function?


I want to create a function fill_table to fill a table dynamically. The tail n of the table is declared in the main() function,

int n = 0;
float* *T;
void show_table(int n) {}
void fill_table(int n) {}

int main() {
    printf(" Table dimension: ");
    scanf("%d", &n);
    fill_table(n);
    show_table(n);
  return 0;
}

I always get this error:

segmentation fault ./a.out

I try mes functions like that:

int n = 0;
float* *T=0;

void show_table(int n){
    printf("Show Table: \n");
    for (int i = 0; i < n; i++) {
      printf("%f ", *(T + i));
    }
}

void fill_table(int n) {
   *T=(float*)calloc(n, sizeof(float));;
  if (!T){
    printf("Memoire not allowe\n");
    exit(0);
  } else {
    for (int i = 0; i < n; i++) {
      printf("\nT[%d]= ", i+1);
      scanf("%f", (T + i));
    }
  }
}

Solution

  • After a lot of trial and error I found this solution:

    • must declare table as

      float* T; //not float* *T;
      
    • function fill_table:

      void fill_table(int n) {
         T=(float*)calloc(n, sizeof(float));;
        if (!T){
          printf("Memoire not allowe\n");
          exit(0);
        } else {
          for (int i = 0; i < n; i++) {
            printf("\nT[%d]= ", i+1);
            scanf("%f", (T + i));
          }
        }
      }
      
    • function show_table:

      void show_table(int n){
          printf("Show Table: \n");
          for (int i = 0; i < n; i++) {
            printf("%f ", *(T + i));
          }
      }