1

从在线练习测试中找到了这个示例代码,该语句如何 strcpy(e1.name, "K");有效,但该语句e1.age=10;无效?任何原因。请澄清。

观察o/pGcc 为:K 0 0.000000

#include<stdio.h>
#include<stdlib.h>

struct employee
{
    char name[15];
    int age;
    float salary;
};
const struct employee e1;

int main()
{
    strcpy(e1.name, "K"); // How strcpy is being used to store values in a    
                          // constant variable e1 .
    //e1.age=10; // not valid 
    printf("%s %d %f", e1.name, e1.age, e1.salary);
    return 0;
}
4

2 回答 2

1

当您访问age时,编译器知道那e1const并禁止写入。

另一方面,当您调用strcpy时,会将指针传递给在(标准)库中实现的函数。因为它只是一个内存地址,所以这个库只会执行它的写操作。

这是不允许的,因为指针实际上是一个const对象的内存地址。编译器会告诉你这是不允许的,只会产生一个警告。严格来说,这个警告应该是一个错误。

于 2013-04-13T17:10:32.803 回答
1

To answer your first question, strcpy is storing the given name in the name field by iterating through the char array as well as the characters of the string literal, saving a copy of each. When the end of the source string is reached, a null char should be found and copied over to the destination. The null char indicates the end of the string, and it is very important that it is copied over. If it is not, your program may read past the end of the array, leading to segfaults or exposing you to buffer overrun attacks. In your case, since the name array has a length of 15, you should not copy over names longer than 14 characters.

The biggest problem with this code is the use of a union instead of a struct. Unions work like structs, but the memory for each field is saved in the same location. For this reason, you should only set one of the fields.

于 2013-04-13T17:11:01.943 回答