所以我写了这个程序,但收到了很多消息,说堆缓冲区溢出问题。但是我看不出有什么问题,有人能帮忙吗。这是代码,当我输入g(任意整数)(任意整数
char **ptr;
void setmine();
/* create a minefield
**/
void setmine(int width , int height) {
ptr = (char **)malloc(sizeof(char)*height);
for (int i = 0; i < height; i++) {
ptr[i] = (char *)malloc(sizeof(char)*width);
}
}
int main(void) {
char line1[20];
char command1;
int width, height;
fgets(line1,20,stdin);
sscanf(line1,"%c %d %d",&command1, &width, &height);
if(command1=='g'){
setmine(width, height);
}
else{
printf("error");
exit(0);
}
char line2[20];
char command2;
int column, row;
fgets(line2,20,stdin);
sscanf("%c %d %d", &command2, &column, &row);
if(command2=='g'){
printf("error");
exit(0);
}
else if(command2=='b'){
setbomb(column,row);
}
else if(command2=='u'){
uncover(column,row, width, height);
}
else if(command2=='f'){
flag(column,row);
}
}
让我帮你一点忙。我修复了代码中的一些错误,并在后面添加了注释。
char **ptr;
// void setmine(); // Parameter were missing here. You don't that anyways, because you defined setmine(int width , int height) before main
/* create a minefield
**/
void setmine(int width , int height) {
ptr = (char **)malloc(sizeof(char*)*height); // Size of pointer to char must be used.
for (int i = 0; i < height; i++) { // Now this should work
ptr[i] = (char *)malloc(sizeof(char)*width);
}
}
int main(void) {
char line1[20];
char command1;
int width, height;
fgets(line1,20,stdin);
sscanf(line1,"%c %d %d",&command1, &width, &height);
if(command1=='g'){
setmine(width, height);
}
else{
printf("error");
exit(0);
}
char line2[20];
char command2;
int column, row;
fgets(line2,20,stdin);
sscanf(line2, "%c %d %d", &command2, &column, &row); // Missing line2
if(command2=='g'){
printf("error");
exit(0);
}
else if(command2=='b'){
setbomb(column,row); // No idea how this is called
}
else if(command2=='u'){
uncover(column,row, width, height); // No idea how this is called
}
else if(command2=='f'){
flag(column,row); // No idea how this is called
}
}
别误会我的意思,但我认为你应该多练习。必须是C吗?我也看到了你对mallocs的尝试。我认为C++更容易一些,这要归功于它在STL中引入的内存管理模板。让我知道。。。