我以数组的名称进行操作,没有出现错误或警告为什么?
我编写了一个期望收到错误以及描述表达式必须是可修改的值的代码,但是我不知道可以动态分配的数组可以修改吗?
{
int* x;
x =(int*) malloc(3 * sizeof(int));
if (x == 0)
{
printf("sorry met an error");
exit(1);
}
x[0] = 0;
x[1] = 1;
x[2] = 2;
printf("%p\n", x);
printf("%d\n", x[0]);
printf("%d\n", sizeof(x));
x++;
printf("%p\n", x);
printf("%d\n", x[0]);
printf("%d\n", x[1]);
printf("%d", sizeof(x));
free(x);
return 0;
}
顺便说一句,这里的免费功能也触发了断点的任何想法?
I wrote a code expecting to receive error along with the description expression must be a modifiable value but i didn't, I don't understand can arrays that were dynamically allocated be modified?
{
int* x;
x =(int*) malloc(3 * sizeof(int));
if (x == 0)
{
printf("sorry met an error");
exit(1);
}
x[0] = 0;
x[1] = 1;
x[2] = 2;
printf("%p\n", x);
printf("%d\n", x[0]);
printf("%d\n", sizeof(x));
x++;
printf("%p\n", x);
printf("%d\n", x[0]);
printf("%d\n", x[1]);
printf("%d", sizeof(x));
free(x);
return 0;
}
By the way the free function here is also triggering a breakpoint any ideas why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
x
是指针到数组中的第一个元素。 (x
不是数组。)由于
x
不是const
,您可以自由修改它。X ++
将其修改为指向数组中的 second 元素。然后,当您尝试释放动态分配的数组(
free(x)
),您将通过free()
一个值malloc
没有给您。因此,调试器引发休息。在尝试释放它之前,要么还原
x
到其先前的值,要么使用其他指针变量播放算术,并仅留下x
。x
is a pointer to the first element in an array. (x
is not an array.)As
x
is notconst
, you are free to modify it.x++
modifies it to point to the second element in the array.When you then attempt to free the dynamically-allocated array (
free(x)
) you are passingfree()
a value thatmalloc
did not give you. Hence the debugger triggering a break.Either restore
x
to its prior value before attempting to free it, or use a different pointer variable to play arithmetic and leavex
alone.用“ GCC”命令行编译:
与命令行链接:
修改的代码,并带有
带有修改的代码的注释,以下是输出
compiling with 'gcc' command line:
linked with the command line:
modified code, with comments
with the modified code, the following is the output