Reputation: 2563
Hi all it's been sometime since I've touched C so I'm really rusty on it. I wrote a small program to create a matrix using two dynamic arrays. However, I'm getting this warning and I don't understand why? I guess I'm not quite sure about pointers to pointers. Can someone help me point out where my problem is? Thanks.
sm.c: In function ‘main’:
sm.c:11:13: warning: initialisation from incompatible pointer type [enabled by default]
sm.c: In function ‘makeMatrix’:
sm.c:27:3: warning: return from incompatible pointer type [enabled by default]
#include <stdio.h>
#include <stdlib.h>
typedef int (**intptr) ();
intptr makeMatrix(int n);
int main(int argc, char *argv[]) {
int n = 2;
int **A = makeMatrix(n);
if(A) {
printf("A\n");
}
else printf("ERROR");
}
intptr makeMatrix(int size) {
int **a = malloc(sizeof *a * size);
if (a)
{
for (int i = 0; i < size; i++)
{
a[i] = malloc(sizeof *a[i] * size);
}
}
return a;
}
Upvotes: 1
Views: 2145
Reputation: 753525
You've got some problems here:
typedef int (**intptr) ();
intptr makeMatrix(int n);
...
int **A = makeMatrix(n);
The intptr
typedef declares a pointer to a pointer to a function that takes an indeterminate number of arguments and returns an int
. A
is not an int
.
You need to write:
int **makeMatrix(int n);
int **A = makeMatrix(n);
Using a typedef
won't help much here.
typedef int **(*intptr)();
That declares a pointer to a function that returns a pointer to a pointer to an int
. But writing
intptr makeMatrix(int n);
would declare that makeMatrix()
returns a pointer to a function, not an int **
.
Upvotes: 3
Reputation: 64740
Your typedef has an extra ()
, making it a zero argument function type. Remove that and you should be good.
Upvotes: 0