&安培;在C数组的操作符定义 [英] & operator definition for arrays in C

查看:97
本文介绍了&安培;在C数组的操作符定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个最近的问题引发了讨论数组和指针中心。问题是参照 scanf函数(%S,&安培;名) VS scanf函数(%S,名字)

A recent question prompted a discussion centering on arrays and pointers. The question was in reference to scanf("%s", &name) vs scanf("%s", name).

有关以下code,微软实际上在VS2010解决此为你(也许更早版本?)

For the following code, Microsoft actually resolves this for you in VS2010 (and maybe earlier versions?),

#include <stdio.h>

int main()
{
    char name[30];

    printf("Scan \"name\" - ");
    scanf("%s", name);
    printf("Print \"&name\" - %s\n", &name);
    printf("Print \"name\"  - %s\n", name);

    printf("Pointer to &name - %p\n", &name);
    printf("Pointer to name  - %p\n", name);

    printf("\n\n");

    printf("Scan \"&name\" - ");
    scanf("%s", &name);
    printf("Print \"&name\" - %s\n", &name);
    printf("Print \"name\"  - %s\n", name);

    printf("Pointer to &name - %p\n", &name);
    printf("Pointer to name  - %p\n", name);

    return 0;
}

难道这实际上是在ANSI C标准定义的,或者是这个允许是依赖编译器?这是否工作,因为MS是治疗一切,C ++?请忽略缓冲区溢出问题现在。

Is this actually defined in the ANSI C Standard, or is this allowed to be compiler dependent? Does this work because MS is treating everything as C++? Please ignore buffer overflow issues for now.

推荐答案

两个名称&放大器;名称应得到相同的结果。严格地说,只有名称是每个C语言标准的有效和&放大器;名称结果不确定的行为,所以你应该肯定使用名称,但在实践中既会工作。

Both name and &name should give the same result. Strictly speaking, only name is valid per the C language standard and &name results in undefined behavior, so you should definitely use name, but in practice both will work.

名称是一个数组,所以当你使用它作为参数传递给函数(如你做的时候,你把它传递给的printf )时,它衰变的指针到它的初始元件(其是字符* 这里)。

name is an array, so when you use it as an argument to a function (as you do when you pass it to printf), it "decays" to a pointer to its initial element (which is a char* here).

&放大器;名称为您提供了数组的地址;这个地址是一样的初始元素的地址(因为可以有一个数组或数组中的元素之间的初始元素之前没有填充字节),所以&放大器;名称名称具有相同的指针值。

&name gives you the address of the array; this address is the same as the address of the initial element (because there can be no padding bytes before the initial element of an array or between elements in an array), so &name and name have the same pointer value.

不过,他们有不同的类型:&放大器;名称的类型为字符(*)[30] (一个指针数组30 字符),而名称,当它衰变为一个指向其初始元素,是类型的char * (指向一个字符,在这种情况下,初始字符数组元素名称)。

However, they have different types: &name is of type char (*)[30] (a pointer to an array of 30 char) while name, when it decays to a pointer to its initial element, is of type char* (a pointer to a char, in this case, the initial char element of the array name).

由于它们具有相同的价值,因为的printf scanf函数功能reinter preT的参数作为一个的char * 无论如何,不​​应该有区别是否传递名称&放大器;名称

Since they have the same value and since the printf and scanf functions reinterpret the argument as a char* anyway, there should be no difference whether you pass name or &name.

这篇关于&安培;在C数组的操作符定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆