admin管理员组文章数量:1122832
I am dynamically allocating a 2D array based on user input for the number of rows and columns, but I encounter a memory access violation when trying to assign values to the maze[i]
in the code. Here's the relevant part of my code.Could anyone help me?
I dynamically allocated memory for a 2D array in C
int main() {
int m, n;
scanf("%d%d", &m, &n);
int** maze = (int**)malloc(sizeof(int*) * (m + 2));
for (int i = 0; i < m + 2; i++) {
maze[i] = (int*)malloc(sizeof(int) * (n + 2));
}
for (int i = 0; i < m + 2; i++) {
for (int j = 0; j < n + 2; j++) {
if (i == 0 || i == m + 1 || j == 0 || j == n + 1)maze[i][j] = 1;//1代表障碍
else {
if (j == n)scanf("%d\n", &maze[i][j]);
else scanf("%d", &maze[i][j]);
}
}
}
for (int i = 0; i < m + 2; i++) {
for (int j = 0; j < n + 2; j++) {
if (j == n)printf("%d\n", maze[i][j]);
else printf("%d ", maze[i][j]);
}
}
}
I am dynamically allocating a 2D array based on user input for the number of rows and columns, but I encounter a memory access violation when trying to assign values to the maze[i]
in the code. Here's the relevant part of my code.Could anyone help me?
I dynamically allocated memory for a 2D array in C
int main() {
int m, n;
scanf("%d%d", &m, &n);
int** maze = (int**)malloc(sizeof(int*) * (m + 2));
for (int i = 0; i < m + 2; i++) {
maze[i] = (int*)malloc(sizeof(int) * (n + 2));
}
for (int i = 0; i < m + 2; i++) {
for (int j = 0; j < n + 2; j++) {
if (i == 0 || i == m + 1 || j == 0 || j == n + 1)maze[i][j] = 1;//1代表障碍
else {
if (j == n)scanf("%d\n", &maze[i][j]);
else scanf("%d", &maze[i][j]);
}
}
}
for (int i = 0; i < m + 2; i++) {
for (int j = 0; j < n + 2; j++) {
if (j == n)printf("%d\n", maze[i][j]);
else printf("%d ", maze[i][j]);
}
}
}
Share
Improve this question
asked Nov 22, 2024 at 12:44
Louis SunLouis Sun
31 silver badge3 bronze badges
6
|
Show 1 more comment
1 Answer
Reset to default 1- Always check the result of malloc
- Always check the result of scanf
- Use meaningful variable names. Avoid
n
,m
,i
,j
- Use
printf
s or assertions when you try to debug your code. - Use objects, not types in
sizeof
- Comment your code.
- Clean all the rubbish behind (use
free
) - Generally - do not be lazy when programming
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main()
{
int totalRows, totalCols;
int** maze = NULL; // Pointer to the maze
int exitCode = EXIT_SUCCESS; // Single exit point
int row;
// Prompt user for the size of the maze
printf("Enter the number of rows and columns: ");
if (scanf("%d,%d", &totalRows, &totalCols) != 2)
{
fprintf(stderr, "Error: Invalid input for rows and columns.\n");
exitCode = EXIT_FAILURE;
goto cleanup;
}
// Allocate memory for the maze (array of row pointers) using calloc
maze = calloc(totalRows + 2, sizeof(*maze));
if (maze == NULL)
{
fprintf(stderr, "Error: Failed to allocate memory for maze rows.\n");
exitCode = EXIT_FAILURE;
goto cleanup;
}
// Allocate memory for each row
for (row = 0; row < totalRows + 2; row++)
{
maze[row] = malloc(sizeof(*maze[row]) * (totalCols + 2));
if (maze[row] == NULL)
{
fprintf(stderr, "Error: Failed to allocate memory for maze columns at row %d.\n", row);
exitCode = EXIT_FAILURE;
goto cleanup;
}
}
// Input maze data
printf("Enter the maze data (without boundaries, row by row):\n");
for (row = 0; row < totalRows + 2; row++)
{
for (int col = 0; col < totalCols + 2; col++)
{
// Set boundary cells
if (row == 0 || row == totalRows + 2 - 1 || col == 0 || col == totalCols + 2 - 1)
{
maze[row][col] = 1; // 1 represents a barrier
}
else
{
// Validate access within non-boundary regions
assert(row > 0 && row <= totalRows);
assert(col > 0 && col <= totalCols);
// Read input for non-boundary cells
if (col == totalCols)
{
if (scanf("%d", &maze[row][col]) != 1)
{
fprintf(stderr, "Error: Invalid input for maze cell at row %d, col %d.\n", row, col);
exitCode = EXIT_FAILURE;
goto cleanup;
}
}
else
{
if (scanf("%d", &maze[row][col]) != 1)
{
fprintf(stderr, "Error: Invalid input for maze cell at row %d, col %d.\n", row, col);
exitCode = EXIT_FAILURE;
goto cleanup;
}
}
}
}
}
// Print the maze layout
printf("Maze layout with boundaries:\n");
for (row = 0; row < totalRows + 2; row++)
{
for (int col = 0; col < totalCols + 2; col++)
{
// Validate access within extended boundaries
assert(row >= 0 && row < totalRows + 2);
assert(col >= 0 && col < totalCols + 2);
// Print maze layout
if (col == totalCols + 2 - 1)
{
printf("%d\n", maze[row][col]);
}
else
{
printf("%d ", maze[row][col]);
}
}
}
cleanup:
// Free allocated memory
if (maze != NULL)
{
for (int row = 0; row < totalRows + 2; row++)
{
free(maze[row]);
}
free(maze);
}
return exitCode;
}
I did not check the logic of your program - only added assertions and did general cleanup.
本文标签: cError in dynamically allocating memory for a 2D arrayStack Overflow
版权声明:本文标题:c - Error in dynamically allocating memory for a 2D array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736303718a1931982.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
m
,n
,i
,j
at that point? – Lundin Commented Nov 22, 2024 at 12:46"%d\n"
as a format string forscanf
is usually not doing what you expect, and is almost never needed. You don't need thatif (j == n)
check. – Some programmer dude Commented Nov 22, 2024 at 12:48