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;
}
you have a mistake in
for(int j=0;i<sizes[i];j++)
it should be
for(int j=0;j<sizes[i];j++)
It would have been easier to spot that if you use more whitespaces like
for (int j = 0 ; i < sizes[i] ; j++)
/* ^ see, here it's very clear now
and also, don't forget to call free
after you are done using the data.
Change this function too
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;i<sizes[i];j++){
printf("%d ",array[i][j]);
}
printf("\n");
}
}
there is no way to determine the count of elements in sizes
, you must pass that as an argument
void print_array(int** array, int* sizes, int rows)
{
for(int i=0;i<rows;i++){
for(int j=0;i<sizes[i];j++){
printf("%d ",array[i][j]);
}
printf("\n");
}
}
note : there is no need to cast malloc
in c, it could hide bugs.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.