This question already has answers here:
Closed 3 years ago.
Is 2d array a double pointer? [duplicate]
(4个答案)
编译以下代码时,我收到警告:
警告:来自不兼容指针类型的赋值
迷宫->mazeValue=mazeValue;
这是解决迷宫的代码。尝试过,但无法识别问题。如果我将
然后按如下方式分配:
然后自己做二维索引,这样就容易多了:
当然
注意:如果您真的希望
(4个答案)
编译以下代码时,我收到警告:
警告:来自不兼容指针类型的赋值
迷宫->mazeValue=mazeValue;
这是解决迷宫的代码。尝试过,但无法识别问题。如果我将
char mazeValue[BUFFERSIZE][BUFFERSIZE]
更改为char \*\* mazeValue**
,程序将被编译为did not execute。Windows抛出警报。#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define BUFFERSIZE (1000)
#define MAZE_ENTRANCE '.'
struct maze {
char ** mazeValue;
int startx, starty;
int numrows;
int initdir;
};
void ReadMaze(struct maze * maze);
int main(int argc, char *argv[]) {
struct maze maze;
ReadMaze(&maze);
printf("Thanks");
//PrintStage(&maze);
return EXIT_SUCCESS;
}
/* Creates a maze from a file */
void ReadMaze(struct maze * maze) {
char buffer[BUFFERSIZE];
char mazeValue[BUFFERSIZE][BUFFERSIZE];
//char workingMaze [BUFFERSIZE][BUFFERSIZE];
//char ** map;
int rows = 0, foundentrance = 0, foundexit = 0;
int columns = 0, i = 0;
/* Determine number of rows in maze */
while ( fgets(buffer, BUFFERSIZE, stdin) ){
//puts(buffer);
columns = strlen(buffer);
/*
for(i=0; buffer[i] != '\0'; i++)
{
//printf("Row: %d\n", rows);
//putchar(buffer[i]);
//printf("\n");
mazeValue[rows][i] = buffer[i];
//putchar(mazeValue[rows][i]);
//printf("\n");
}
*/
strcpy(mazeValue[rows], buffer);
for ( i = strlen(mazeValue[rows]) - 1; isspace(mazeValue[rows][i]); --i )
mazeValue[rows][i] = 0;
/* Check for entrance and save the location if it finds */
if ( !foundentrance && rows == 0) {
i = 0;
printf("rows %d\n", rows );
printf("i %d\n", i );
while ( mazeValue[rows][i] != MAZE_ENTRANCE && mazeValue[rows][i++] ){
if ( mazeValue[rows][i] == MAZE_ENTRANCE ) {
maze->startx = i;
maze->starty = rows;
foundentrance = 1;
}
}
}
++rows;
}
maze->mazeValue = mazeValue;
maze->numrows = rows;
printf("maze->startx %d\n", maze->startx);
printf("maze->starty %d\n", maze->starty );
printf("\n");
printf("Stage 1\n");
printf("=======\n");
printf("maze has %d rows and %d columns\n\n", rows, columns);
i=0;
int j;
for(i=0; i<=rows; ++i)
{
for(j=0; j<=columns; ++j){
printf("%c", mazeValue[i][j]);
printf("%c", mazeValue[i][j]);
}
printf("\n");
}
printf("\n");
printf("foundentrance: %d\n", foundentrance);
}
最佳答案
即使任务成功了,你也做不到。您试图存储一个本地数组,稍后再使用它,这是不允许的,并且会给您带来未定义的行为。
您需要在结构中堆分配(使用malloc()
)数据,而不是使用本地数组。
首先将结构成员更改为纯字符指针:
char *mazeValue; /* Single-star! */
然后按如下方式分配:
maze->mazeValue = malloc(BUFFERSIZE * BUFFERSIZE);
然后自己做二维索引,这样就容易多了:
maze->mazeValue[y * BUFFERSIZE + x] = '?';
当然
x
和y
必须都在0
和BUFFERSIZE - 1
之间。注意:如果您真的希望
BUFFERSIZE
是常量,可以直接在结构中声明数组,返回到2D数组:char mazeValue[BUFFERSIZE][BUFFERSIZE];
关于c - 警告:来自不兼容指针类型的赋值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37317895/
10-12 02:04