作者DarkKiller (System hacked)
看板C_and_CPP
标题Re: [问题] char *str="test"是const字串的问题
时间Thu Nov 17 17:48:47 2005
※ 引述《Aligu1009 (=.=)》之铭言:
: 请问各位
: char *str="test";
: 这种写法
: 这个字串会被当作是const而不能更改
: 类似的写法如:
: char str[] = "test";
: 这个字串就是可变更的了
: C为什麽要对第一种写法做这种限制呢? 谢谢
因为要提供两种 implement 的方法?前者会被放到 read-only section,後者
会被放到 stack。
这是 char.c:
#include <stdio.h>
int main(void)
{
char *a1 = "test123456";
char a2[] = "test654321";
}
这是 gcc -O0 -S char.c 所产生出来的 char.s:
gslin@netnews [~/work/C] [17:41/W3] cat char.s
.file "char.c"
.section .rodata
.LC0:
.string "test123456"
.LC1:
.string "test654321"
.text
.p2align 2,,3
.globl main
.type main, @function
main:
pushl %ebp
movl %esp, %ebp
pushl %edi
pushl %esi
subl $32, %esp
andl $-16, %esp
movl $0, %eax ; 这五行是什麽鬼... 该不会 -O0
addl $15, %eax ; 就是这麽废吧 XD
addl $15, %eax
shrl $4, %eax
sall $4, %eax
subl %eax, %esp ; 空出一块 stack space
movl $.LC0, -12(%ebp)
leal -40(%ebp), %edi ; %edi = destination
movl $.LC1, %esi ; %esi = source
cld ; copy order
movl $11, %ecx ; copy 11 bytes
rep ; 这两个指令就是 copy 的动作
movsb
leal -8(%ebp), %esp
popl %esi
popl %edi
leave
ret
.size main, .-main
.ident "GCC: (GNU) 3.4.4 [FreeBSD] 20050518"
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.113.54.119