[英]segmentation fault in this pointers program in C
I keep getting a segmentation fault (core dumped) message whenever I try to run this C program. 每当我尝试运行此C程序时,我总是收到分段错误(核心已转储)消息。
#include <stdio.h>
int main()
{
int i = 200, *p, *q, *r;
p,r = &i;
q = p;
*q = *p + 1;
printf("*p = %d\n", *p);
printf("*r = %d\n", *r);
return 0;
}
It didn't have any r
s at first but I had to add r
s as an alias to i
and then Add print statements to output the dereferenced values of q
and r
. 它最初没有任何
r
,但是我不得不将r
s作为别名添加到i
,然后添加print语句以输出q
和r
的解引用值。
In your code 在你的代码中
p,r = &i;
does not assign p
, it leaves p
uninitialized. 没有分配
p
,它使p
未初始化。 Next, the very moment you dereference p
(and q
also, as it was assigned with the value of p
) you hit undefined behavior , as you're dereferencing invalid memory. 接下来,在取消引用
p
(也为q
分配了p
的值)的那一刻,您遇到了不确定的行为 ,因为您正在取消引用无效的内存。
You need to use 您需要使用
p = r = &i;
Compile your code with proper warnings enabled and, with your code, you should see something similar to 在启用适当警告的情况下编译您的代码,并在代码中看到类似以下内容
warning: left-hand operand of comma expression has no effect [-Wunused-value]
警告:逗号表达式的左操作数无效[-Wunused-value]
p,r = &i; ^
Use this: 用这个:
p = &i;
r = &i;
instead of 代替
p,r = &i;
Uninitialized pointer is bad. 未初始化的指针是错误的。
//I write that as an answer because i still don't have 50 reputation
1: I didn't understand what do you want that the program will do. 1:我不明白您希望程序执行什么操作。 the use of q and r is useless.
q和r的使用是无用的。
2: p,r=&i;
2:
p,r=&i;
is not a good command. 这不是一个好命令。 use
p=r=&i
or p=&i; r=&i;
使用
p=r=&i
或p=&i; r=&i;
p=&i; r=&i;
or p=&i; r=p;
或
p=&i; r=p;
p=&i; r=p;
i have made the correction in your code and it is working fine please have look into it. 我已经在您的代码中进行了更正,并且工作正常,请仔细检查。
`#include <stdio.h>
int main()
{
int i = 200, *p, *q, *r;
p = &i;
r = &i;
q = p;
*q = *p + 1;
printf("*p = %d\n", *p);
printf("*r = %d\n", *r);
return 0;
}`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.