Let each row have a different size column, where all the elements are 0. I tried it on my own, and now my code just achieves zero for all elements with the same number of columns in each row. I wanted my code to allow the user to control the number of columns per row. How to achieve it on my code? Here is my code. #include <stdio.h> #include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
int** make_zeros(int rows, int cols) {
int** zeros_array; // create a double pointer nameed zeros_array
zeros_array = malloc(sizeof(int)*rows); // set space for zeros_array
for(int row = 0; row < rows; row ) {
zeros_array[row] = malloc(sizeof(int)*cols); // set space for zeros_array for each row
for (int col = 0; col < cols; col ) {
zeros_array[row][col] = 0; // the element is equal to zero;
}
}
// return the result
return zeros_array;
}
int main(void) {
printf("How many rows ?: "); // let user enter the nums of rows
int rows = 0;
scanf("%d",&rows);
printf("How many columns ?: "); // let user enter the nums of cols
int cols = 0;
scanf("%d",&cols);
int **zeros; // create a double pointer
zeros = make_zeros(rows,cols); // lead to the function make_zeros
for (int r = 0; r < rows; r ) {
for (int c = 0; c < cols; c ) {
printf("%d ",zeros[r][c]); // print the elements of all of array that stored on double pointer
}
printf("\n"); // move to the new line
}
return 0;
}
Thank you all for your help.
CodePudding user response:
You're not allocating enough memory:
zeros_array = malloc(sizeof(int)*rows);
This allocates space for rows
elements of type int
. You need rows
elements of type int *
. On most systems, int
is 4 bytes and int *
is 8 bytes. So you end up writing past the end of allocated memory which triggers undefined behavior.
Specify the correct type you want to allocate space for:
zeros_array = malloc(sizeof(int *)*rows);
CodePudding user response:
You could use scanf inside your make_zeros function inside the for loop and ask the user to input number of columns in that particular row.