Difference between char *str=“STRING” and char str[] = “STRING”

char str[] = "string";

sizeof(str) 的值为7。

char *str = "string";

sizeof(str)的值为4(指针的大小)。

这两者的区别是什么? 为什么会这样?下面是别的地方看到的讨论,看完后就明白了。

===============================分====================================

The two declarations are not the same.

char ptr[] = "string"; declares a char array of size 7 and initializes it with the characters
s ,t,r,i,n,g and \0. You are allowed to modify the contents of this array.

char *ptr = "string"; declares ptr as a char pointer and initializes it with address of string literal"string" which is read-only. Modifying a string literal is an undefined behavior. What you saw(seg fault) is one manifestation of the undefined behavior.


========================================================
And a sizeof(ptr) will give different results to for the different declarations. The first one will return the length of the array including the terminating null character. The second will return the length of a pointer, usually 4 or 8. 


It's also true in the second place that the contents of ptr can be changed. But the contents are the pointer to the literal, not the characters. 


+1, great answer. It is also true and important to understand that with char *ptr = "string"; the ptrcan be pointed at something else and can therefor be 'changed' in what it is pointing at but the characters"string" is a literal and cannot change. 


It would also be worth mentioning the performance issues. Declaring an initialized automatic array variable will fill the entire array contents every time the variable comes into scope. Declaring an initialized automatic pointer variable will simply assign the pointer (a single word write) when the variable comes into scope. If the string is long or the block is entered often (like each iteration of a loop), the difference could be very significant!


@AmigableClarkKant, actually, sizeof(ptr) is not the length of the array unless ptr is declared as a char array. If ptr is defined as an int arryay with 3 elements, sizeof(ptr) will return the sum ofsizeof(int) of each element. 

原文地址:http://stackoverflow.com/questions/3862842/difference-between-char-str-string-and-char-str-string

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值