我在 C 中得到了这段代码。在 GCC-4.8.1 上运行它时出现了一个奇怪的行为(编译时没有警告和错误)。
当我输入 r 和 c 作为任何整数 (r=c) 时,我输入动态分配的二维数组,但是当我输入 r 和 c 时,5 & 4 分别 (r>c),我在 Windows 中收到一个不发送错误。我相信这可能是由于某些非法指针间接寻址造成的,但我无法弄清楚它是什么。
你能帮我找到它吗?
代码如下:
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
int main()
{
int no_of_test_cases;
int r, c;
int i,j;
printf("Enter the no of test cases:\n");
scanf("%d", &no_of_test_cases);
printf("Enter the no of rows:\n");
scanf("%d", &r);
printf("Enter the no of columns:\n");
scanf("%d", &c);
r+=2;
c+=2;
//Dynamically allocate the 2D array
char **string_pattern;
string_pattern = (char**)malloc(r* sizeof(char*));
if(string_pattern==NULL)
{
printf("Not enough memory");
exit(0);
}
for(i=0; i<c; i++)
{
string_pattern[i] = (char*)malloc(c* sizeof(char));
if(string_pattern[i]==NULL)
{
printf("Not enough memory");
exit(0);
}
}
//Now lets put a wall around with the character '#'
j=0;
for(i=0; i<r; i++)
{
string_pattern[i][j]='#';
}
j=0;
for(i=0; i<c; i++)
{
string_pattern[j][i]='#';
}
j=c-1;
for(i=0; i<r; i++)
{
string_pattern[i][j]='#';
}
j=r-1;
for(i=0; i<c; i++)
{
string_pattern[j][i]='#';
}
printf("haha");
//Now lets input the array
for(i=1; i<r-1; i++)
{
for(j=1; j<c-1; j++)
{
scanf(" %c",&string_pattern[i][j]); /*whitespace preceding the %c is to skip
a non whitespace character in the input buffer*/
}
}
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
printf("%c",string_pattern[i][j]);
}
printf("\n");
}
return 0;
}
最佳答案
眼前的问题是,在您的分配循环中,您正在为每一行分配内存,但您正在计算列数 ( i < c
):
for(i=0; i<c; i++) {
string_pattern[i] = (char*)malloc(c* sizeof(char));
...
这是必须的
for(i=0; i < r; i++)
^^
否则您正在访问非法索引。 **string_pattern
为给定的行数分配足够的指针,但是为每一行分配内存的 for 循环访问无效内存(例如 r = 3,c = 4):
char **string_pattern = malloc(r* sizeof(char*));
+----+
| 0 |
+----+
| 1 |
+----+
| 2 |
+----+
. 3 . <= Invalid index for c=3 in for-loop
......
关于c - 程序中的指针误导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26709565/