"生命周期"串用C字面 [英] "life-time" of string literal in C

查看:144
本文介绍了"生命周期"串用C字面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不会受下面的函数返回的指针不可访问?

Wouldn't the pointer returned by the following function inaccessible?

char *foo( int rc ) 
{
    switch (rc) 
    {
      case 1:           return("one");
      case 2:           return("two");
      default:           return("whatever");
    }
}

因此​​,在C / C ++的局部变量的生命周期实际上只在功能,对不对?这意味着,在的char *富(INT)终止,则返回不再指针意味着什么?

So the lifetime of a local variable in C/C++ is practically only within the function, right? Which means, after char* foo(int) terminates, the pointer it returns no longer means anything?

我有点困惑局部变量的寿命。
谁能给我一个很好的澄清?

I'm a bit confused about lifetime of local var. Could anyone give me a good clarification?

推荐答案

是的,一个局部变量的寿命范围(在{ } )的创建它。结果
局部变量有自动或本地存储。结果
自动的,因为它们会被自动destoryed一旦在其中创建它们两端的范围。

Yes, lifetime of an local variable is within the scope({,}) in which it is created.
Local variables have automatic or local storage.
Automatic because they are automatically destoryed once the scope within which they are created ends.

不过,你在这里什么是字符串文字,这是在只读存储器中定义的执行分配。字符串文字是由局部变量不同,它们在整个程序lifetime.They仍然存活具有的静态病程 [参考1] 寿命。

However, What you have here is an string literal, which is allocated in an implementation defined read only memory. String literals are different from local variables and they remain alive throughout the program lifetime.They have static duration [Ref 1] lifetime.

一个忠告!结果
但是请注意,任何试图修改字符串的内容literal是未定义的行为。
用户程序不允许修改字符串的内容。结果
因此,它总是鼓励使用常量同时声明字符串。

A word of caution!
However, note that any attempt to modify the contents of an string literal is an Undefined Behavior. User programs are not allowed to modify contents of a string literal.
Hence, it is always encouraged to use a const while declaring a string literal.

const char*p = "string"; 

而不是

char*p = "string";    

事实上,在C ++中,它是pcated声明一个字符串而不常量虽然不是在C德$ P $。不过,声明字符串和常量给你的优点是编译器通常会为您提供的情况下,您试图修改字符串中的第二种情况下的文字警告。

In fact, in C++ it is deprecated to declare a string literal without the const though not in c. However, declaring a string literal with a const gives you the advantage that compilers would usually give you a warning in case you attempt to modify the string literal in second case.

示例程序

Sample program:

#include<string.h> 
int main() 
{ 
    char *str1 = "string Literal"; 
    const char *str2 = "string Literal"; 
    char source[]="Sample string"; 

    strcpy(str1,source);    //No warning or error just Uundefined Behavior 
    strcpy(str2,source);    //Compiler issues a warning 

    return 0; 
} 

输出:

CC1:警告被视为错误结果
   prog.c中:在函数'主':结果
   prog.c中:9:错误:传递的strcpy的参数1丢弃了指针目标类型的限定

cc1: warnings being treated as errors
prog.c: In function ‘main’:
prog.c:9: error: passing argument 1 of ‘strcpy’ discards qualifiers from pointer target type

注意编译器警告对于第二种情况,但不是第一个。

Notice the compiler warns for the second case but not for the first.

编辑:要回答在Q被要求一对夫妇的用户在这里:

To answer the Q being asked by a couple of users here:

什么是处理不可分割的文字?结果
换句话说就是这个code有效的:

What is the deal with integral literals?
In other words is this code valid:

int *foo()
{
    return &(2);
} 

答案是,没有此code是无效的,它是非法的构造和放大器;会给出一个编译器错误。结果
是这样的:

The answer is, No this code is not valid, it is ill-formed & will give an compiler error.
Something like:

prog.c:3: error: lvalue required as unary ‘&’ operand

字符串文字是左值,即:你可以把一个字符串的地址,但不能改变它的内容结果。
然而,任何其他文字( INT 浮动字符等)是R值(C标准使用术语的的前pression值的这些)及其地址不能在所有服用。

String literals are l-values, i.e: You can take the address of an string literal but cannot change it's contents.
However, any other literals(int,float,char etc) are r-values(c standard uses the term the value of an expression for these) & their address cannot be taken at all.

[参考1] C99标准6.4.5 / 5字符串文字 - 语义:

在翻译阶段7,零值字节或code追加到从字符串字面量或导致每个多字节字符序列。 的多字节字符序列,然后用来初始化静态存储时间和长度刚好足够的数组包含序列。对于字符串常量,数组元素具有char类型,并与多字节字符序列的各个字节被初始化;宽字符串,数组元素具有wchar_t类型,并与宽字符序列进行初始化...

In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence; for wide string literals, the array elements have type wchar_t, and are initialized with the sequence of wide characters...

这是不确定的,这些阵列是否提供了不同的元素具有适当的值。 如果该程序试图修改这样的阵列,这种行为是未定义

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

这篇关于&QUOT;生命周期&QUOT;串用C字面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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