[英]What is the difference between these two pointer assignments in C?
I have been doing a lot of research and also playing around with code, but I'm still confused with this: Why is case 1 erroring?我一直在做很多研究,也玩过代码,但我仍然对此感到困惑:为什么案例 1 会出错?
Case 1:情况1:
int arr[] = {0,4,7};
int *p = arr[0]; // pointer points to the first element in the array
printf("%d", ++*p);
// This results in Segmentation fault
Case 2:案例2:
int arr[] = {0,4,7};
int *p = arr; // pointer points to the first element in the array
printf("%d", ++*p);
// This prints 1
In case 1: arr[0]
is an int
value.在情况 1 中: arr[0]
是一个int
值。 int *p = arr[0];
is an error.是一个错误。
What is the difference between these two pointer assignments in C? C中这两个指针赋值有什么区别?
Firstly, one thing common with both is that neither is an assignment.首先,两者的共同点是两者都不是作业。
int *p = arr[0]; // pointer points to the first element in the array
The comment here is wrong.这里的评论是错误的。 arr
is an array of int
. arr
是一个int
数组。 arr[0]
is the first element of that array. arr[0]
是该数组的第一个元素。 It is an int
.它是一个int
。 int *p = arr[0]
is an attempt at initialising a pointer with the value that is stored in the array. int *p = arr[0]
尝试使用存储在数组中的值初始化指针。 However, the type doesn't match since the value is not a pointer.但是,类型不匹配,因为该值不是指针。 int
is not implicitly convertible to int*
and therefore the program is ill-formed. int
不能隐式转换为int*
,因此程序格式错误。
A standard conforming language implementation is required to diagnose this issue for you.需要一个符合标准的语言实现来为您诊断这个问题。 This is what my compiler says:这是我的编译器所说的:
error: invalid conversion from 'int' to 'int*'
Why is case 1 erroring?为什么情况 1 会出错?
If the program even compiles, you are initialising a pointer with the value 0. This likely means that it is a null pointer and that it doesn't point to any object.如果程序甚至可以编译,则您正在初始化一个值为 0 的指针。这可能意味着它是一个空指针并且它不指向任何对象。 ++*p
attempts to indirect through this null pointer and access the non-existing integer. ++*p
尝试通过这个空指针间接访问不存在的整数。
int *p = arr; // pointer points to the first element in the array
Comment here is correct.这里的评论是正确的。
I guess it is throwing an error because you did not use '&' before assigning the value to the pointer.我想它会抛出一个错误,因为在将值分配给指针之前没有使用 '&' 。 As it is a pointer so you can not assign a value to it.因为它是一个指针,所以你不能给它赋值。 You can only use it to store addresses.您只能使用它来存储地址。 I coded it in C++ and here is the correct form.I guess it helps.我用 C++ 编码它,这是正确的形式。我想它有帮助。
#include <iostream>
using namespace std;
int main(){
int arr[] = {0,4,7};
int *p = &arr[0]; //you are missing '&' before array[0]
printf("%d", ++*p);
system("pause");
// This prints 1
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.