0

I am trying to allocate memory for a 3 by 5 2-dimensional array. When compiling this code, I receive this error in the cygwin terminal:

2darraymalloc.c: In function 'main':
2darraymalloc.c:7:9: warning: incompatible implicit declaration of built-in function 'malloc'    a[i] = malloc(sizeof(int)*5);
#include <stdio.h>

void main() {
    int *a[3], i, j;

    for (i = 0 ; i < 3 ; i++) {
        a[i] = malloc(sizeof(int) * 5);
    }

    for (i = 0 ; i < 3 ; i++) {
        for (j = 0 ; j < 5 ; j++) {
            a[i][j] = i + 2 * j;
        }
    }

    printf("%d", *a[2]);
}
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Michael
  • 3,093
  • 7
  • 39
  • 83

2 Answers2

0

You need to include stdlib.h, also always check if malloc() did return a valid pointer, on error it returns NULL, and main() should return int, a valid signature for main() in your case could be int main(void).

Always enable compilation warnings, add this to the gcc invocation

gcc -Wall -Wextra -Werror -o my-program-name my-source.c
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
0

In C functions that do not have a prototype defined are assumed, by default, to return int. Since you did not include stdlib.h it leaves malloc() undeclared and therefore assumed to return int. The statement a[i] = malloc(...) has on the left side a int pointer and on the right side an int - thus the error message.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
AndersK
  • 35,813
  • 6
  • 60
  • 86