I am teaching myself C and have been working my way through a book. I have finished the book and I am now starting to create my own program. I need to be able to create an matrix of size NxN however I can't get malloc to allocate the memory for the matrix.
I have tried everything I can think of, but nothing seems to work. I had a quick search and found that malloc doesn't have the capability to allocate 2D arrays, saying you have to allocate each dimension one at a time and also that one of the dimensions needs to be known before hand - which kind of defeats the object for a NxN matrix (having said that even when creating x,y coordinates for each of the N points, it still throws a warning and I wouldn't say I was confident then that the memory was being freed).
This is the code that I have:
- Code: Select all
#include <stdio.h>
int N;
double **nodeCoord;
int main()
{
/* Define external variables */
extern int N;
extern double **nodeCoord;
N = 2;
nodeCoord = (double**) malloc(N);
free(nodeCoord);
return 0;
}
The above code throws a warning saying:
main.c:32: warning: incompatible implicit declaration of built-in function ‘malloc’
main.c:40: warning: incompatible implicit declaration of built-in function ‘free’
I don't know what this means, but I would assume it's because malloc returns an integer pointer and therefore cannot be cast to a double**. So I tried changing the
- Code: Select all
nodeCoord = (double**) malloc(N);
line to
- Code: Select all
&nodeCoord = (double*) malloc(N);
I also tried changing it to:
- Code: Select all
*nodeCoord = (double*) malloc(N);
However, both of those gave the same warning message. Normally I'm not that worried about warning messages, however when I check to see if the memory isn't free'd simply by outputting some values, it still outputs the correct values even after freeing the memory.
I have also tried the following:
- Code: Select all
typedef struct
{
double *x;
double *y;
} coord;
then changing the nodeCoord line to
- Code: Select all
nodeCoord.x = (double*) malloc(N);
nodeCoord.y = (double*) malloc(N);
where nodeCoord is defined by: coord nodeCoord;. This also gave the same warning message and didn't free the memory correctly - this I find quite strange as surely it shud call malloc return the integer pointer which is then cast to a double pointer, which is exactly what the x member of nodeCoord struct is.
I also tried creating an array of pointers of size 2:
- Code: Select all
double *nodeCoord[2];
then use malloc on each element. However this also gave the same warning.
I honestly cannot see what I am doing wrong and am not 100% sure that I can even create a two dimensional array using malloc? Alternatively, does anyone know of an alternate way to create 2D arrays in C?
Any help is greatly appreciated.
Finally, would it be possible for a C tutorial to be covered in Linux Format?
Thanks,
Chris