Reputation: 21
I'm learning C at the moment and tried to write this function
int *create_matrix(int n) {
int *matrix = malloc(n*n*sizeof(int));
srand(time(NULL));
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
matrix[i][j] = rand()%10;
}
}
return matrix;
}
why does this fail to compile? its complaining about matrix[i][j]
is not an pointer/array. but I've just declared it as an pointer six lines above...
Upvotes: 0
Views: 6013
Reputation: 9619
You've declared matrix
as a one-dimensional array, and not as a two-dimensional array.
So use it like:
for(int i=0; i<n*n; ++i)
matrix[i] = //whatever;
If you really need two-dimensional array, you need to use double pointers
:
int **matrix = malloc(n * sizeof(int *)); // notice the double pointer
// ....
// ....
for (i = 0; i < n; i++)
{
matrix[i] = malloc(sizeof(int) * n);
// ....
}
Upvotes: 2
Reputation: 41055
You want two dimensions, then you need a pointer to pointer (not a single pointer):
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int **create_matrix(int n)
{
int **matrix = malloc(n * sizeof(int *));
srand(time(NULL));
int i, j;
for (i = 0; i < n; i++) {
matrix[i] = malloc(sizeof(int) * n);
for (j = 0; j < n; j++) {
matrix[i][j] = rand()%10;
}
}
return matrix;
}
int main(void)
{
int **matrix = create_matrix(5);
return 0;
}
Upvotes: 1
Reputation: 529
What it's really complaining about is, the matrix[i] is not a pointer/array. You've only created a 1-dimensional array, you either can access it directly like
matrix[i * n + j] = rand() % 10;
or go ahead, do it cleanly, and redo the array, so it will be 2-dimensional. You'll need to use pointer to a pointer (for every member in line - one row)
int **matrix
but you'll have to loop trough the
*matrix
to malloc each row by itself.
Look up on 2-dimensional arrays.
//EDIT: Also, move the srand() to the beginning of the file. You don't want to srand() with every new matrix.
Upvotes: 1
Reputation: 57346
You declare matrix
as a one-dimensional array. You need to either store the data in it as such, i.e.
matrix[i * n + j] = rand() % 10;
Or declare it as a two-dimensional array and allocate memory accordingly.
int** matrix = malloc(n * sizeof(int*));
int i, j;
for (i = 0; i < n; i++) {
matrix[i] = malloc(n * sizeof(int));
for (j = 0; j < n; j++) {
matrix[i][j] = rand() % 10;
}
}
Upvotes: 1
Reputation: 500943
It's a 1D array, so you have to treat it as a 1D array, and not as 2D.
You can of course still store your n x n
elements in it:
matrix[i * n + j] = rand() % 10;
If you prefer, you can set up a 2D structure by following the advice given in How do I work with dynamic multi-dimensional arrays in C?
By the way, you probably don't want to be calling srand()
every time you create a matrix. If you call create_matrix()
twice in quick succession, you could end up getting the same "random" matrix. Call srand()
once at the start of your program.
Upvotes: 7