I have to create a "2D Array" with x rows (User can decide how many) and for each row there should be a random amount of columns, which will be generated random, so it will look like this:
2 - 4 - 6
1 - 2 - 8 - 9 - 2 - 3
1 - 2
the amount of columns for each row will be saved in sizes[i]. The numbers in the 2d array will be generated randomly. I looked here through stackoverflow, and finding some solutions regarding dynamic memory allocation, but somehow I always end up with a 'Segmentation fault' and I can't really see a major flaw in my code. So any help would be appriciated. :)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int** create_array(int* sizes, int rows){
int** array;
array=(int**) malloc(rows*sizeof(int*));
for(int i=0;i<rows;i++){
array[i]=(int*) malloc((sizes[i])*sizeof(int));
}
for(int i=0;i<rows;i++){
for(int j=0;j<sizes[i];j++){
array[i][j]=(((double) rand() / (RAND_MAX))*20);
}
}
return array;
}
void print_array(int** array, int* sizes){
int rows=sizeof(sizes)/sizeof(sizes[0]);
for(int i=0;i<rows;i++){
for(int j=0;j<sizes[i];j++){
printf("%d ",array[i][j]);
}
printf("\n");
}
}
int main(int argc, char const *argv[])
{
int rows = 0;
srand(time(NULL));
printf("Wie viele Zeilen möchten Sie erzeugen?");
scanf("%d",&rows);
int sizes[rows];
for(int i=0;i<rows;i++){
sizes[i]=(((double) rand() / (RAND_MAX))*9+1);
printf(" %d ",sizes[i]);
}
int** arr;
arr=create_array(sizes,rows);
print_array(arr,sizes);
return 0;
}
create_array, this looks suspicions:for(int j=0;i<sizes[i];j++){(I guess you want to comparej, notiwithsizes[i]). The same inprint_array.for(int j=0;i<sizes[i];j++){sizeof(sizes)/sizeof(sizes[0])will give you "bad" result, you cannot calculate the size of array (passed as pointer).structs instead, but the idea still remains the same - you need to have the size somewhere).structand store the extra information in it, and then only pass an array ofstructas a pointer to the functions, but I would recommend you don't make it more complex than it is, just pass the extra parameter.