简体   繁体   English

为什么指向int数组的未初始化指针可以分配变量的值?

[英]Why can uninitialized pointer to int array be assigned variable's value?

I have read answers to questions like why a pointer can be assigned value? 我已经阅读了一些问题的答案,例如为什么可以为指针分配值? however I'm still a bit confused about changing the values of pointers. 但是我对更改指针的值仍然有些困惑。 Some of the comments don't seem to be completely accurate, or maybe it's implementation specific. 有些评论似乎并不完全准确,或者可能是针对具体实现的。 (example: a[1] is exactly the same as writing *(a + 1). Obviously you can write *a = 3 since a is int*, so you can also write *(a + 1) = 3, so you can also write a[1] = 3 ). (例如: a[1] is exactly the same as writing *(a + 1). Obviously you can write *a = 3 since a is int*, so you can also write *(a + 1) = 3, so you can also write a[1] = 3 )。

Writing *a = 3 produces a warning: initialization makes pointer from integer without a cast. 写入*a = 3会产生警告:初始化会使指针从整数开始而不进行强制转换。 As well as a segfault. 以及段错误。

My question is as follows. 我的问题如下。

int main(void)
{
    int b = 5, c = 10;
    int *a = b;

    *a = c; /* Will not work. (Should technically change the value of b to 10, leaving the pointer still pointing to b.) */
    printf("%d\n", *a);
    return 0;
}

The above example will not work, and will produce a segfault, but the following works for some reason I am not aware of. 上面的示例将不起作用,并且将产生一个段错误,但是以下原因是我不知道的某些原因。

int main(void)
{
    int a[10], i;
    for (i = 0; i < 10; ++i) {
        *(a + i) = i; /* Supposedly the same logic as '*a = c;', but works*/
    }

    for (i = 0; i < 10; ++i) {
        printf("%d\n", *(a + i));
    }

    return 0;
}

Thanks for your time and efforts. 感谢您的时间和精力。

**EDIT: Thank you for the answers, since it is *a = &b (I knew this (typo), but now the second example with the loop is unclear), the array indices are treated as variables, not as addresses I presume? **编辑:谢谢您的回答,因为它是* a =&b(我知道这个(典型),但是现在带有循环的第二个例子尚不清楚),数组索引被视为变量,而不是我假定的地址?

This: 这个:

int b = 5, c = 10;
int *a = b;

Doesn't work. 不起作用 You think the second line means this: 您认为第二行意味着:

int *a;
*a = b;

But it doesn't. 但事实并非如此。 It means this: 这意味着:

int *a;
a = b;

The above error means that when you do this: 上面的错误意味着您执行以下操作:

*a = c;

Your program crashes (or maybe not, undefined behavior!), because a is an invalid pointer (it points to address 5, which is wrong in many ways). 您的程序崩溃(或者可能不是,未定义行为!),因为a是无效的指针(它指向地址5,这在许多方面都是错误的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM