#include <stdio.h> #include <stdlib.h> int main(){ int rows; int cols; printf("\nEnter…
Private research annotation
Sign in to add a private research label or note.
- User
#include <stdio.h> #include <stdlib.h>
int main(){ int rows; int cols; printf("\nEnter the number of columns: "); while(scanf("%d", &cols) != 1){ printf("\nTry again: "); } printf("\nEnter the number of rows: "); while(scanf("%d", &rows) != 1){ printf("\nTry again: "); }
codeint* row_indexes = malloc(sizeof(int*) * rows); int** two_d_array = &row_indexes[0]; for(int i = 0; i < rows; i++){ row_indexes[i] = malloc(sizeof(int) * cols); } for(int i = 0; i < rows; i++){ for(int j = 0; i < cols; i++){ two_d_array[i][j] = 0; } } for(int i = 0; i < rows; i++){ for(int j = 0; i < cols; j++){ printf("%d ", two_d_array[i][j]); } printf("\n"); } return 0;}
segmentation fault. How to fix
- Assistant
There are a couple of issues in the code that are causing a segmentation fault.
-
In the nested loops where you are initializing the elements of
two_d_arrayto 0, you have a typo in the inner loop condition. You are mistakenly usingiinstead ofj. Update the inner loop condition toj < colsinstead ofi < colsin both loops. -
In the inner loops where you are printing the values of
two_d_array, you have made the same typo by usingiinstead ofj. Update the inner loop condition toj < colsinstead ofi < colsin both loops.
Here is the corrected code:
-
- User
#include <stdio.h> #include <stdlib.h>
int main(){ int rows; int cols; printf("\nEnter the number of columns: "); while(scanf("%d", &cols) != 1){ printf("\nTry again: "); } printf("\nEnter the number of rows: "); while(scanf("%d", &rows) != 1){ printf("\nTry again: "); }
codeint* row_indexes = malloc(sizeof(int*) * rows); int** two_d_array = &row_indexes[0]; for(int i = 0; i < rows; i++){ row_indexes[i] = malloc(sizeof(int) * cols); } for(int i = 0; i < rows; i++){ for(int j = 0; j < cols; j++){ two_d_array[i][j] = 0; } } for(int i = 0; i < rows; i++){ for(int j = 0; j < cols; j++){ printf("%d ", two_d_array[i][j]); } printf("\n"); } return 0;}
segmentation fault. How to fix
- Assistant
The issue causing the segmentation fault in your code is related to the way in which you are assigning memory to
row_indexesandtwo_d_array. The allocation of memory for a 2D array is incorrect.The correct way to allocate memory for a 2D array in your code is as follows:
- Allocate memory for
row_indexesto storerowspointers (each pointing to a row). - Allocate memory for each row individually and assign the pointer to each row in
row_indexes. - Access the 2D array elements correctly using the pointer to each row.
Here is the corrected code:
c - Allocate memory for