initial pointer [expert c]

本文阐述了在定义中初始化数组与指针时的不同行为,特别指出数组初始化时的可写性与指针初始化时的读取只读特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   initial differece between pointer and array

           Both arrays and pointers can be initialized with a literal string in their definition. Although these cases look the same, different things are happening. A pointer definition does not allocate space for what's pointed at, only for the pointer, except when assigned a literal string. For example, the definition below also creates the string literal:

                                     char *p = "breadfruit";
Note that this only works for a string literal. You can't expect to allocate space for, for example, a float literal:
                                   float *pip = 3.141;     /* Bzzt! won't compile */

         A string literal created by a pointer initialization is defined as read-only in ANSI C; the program will  exhibit undefined behavior if it tries to change the literal by writing through p. Some implementations put string literals in the text segment, where they will be protected with read-only permission.

                eg:          char *s = "hello world";

                                  *s = 'w';

    would generate an error when running the program.

    An array can also be initialized with a string literal:
                          char a[] = "gooseberry";
     In contrast to a pointer, an array initialized by a literal string is writable. The individual characters can later be changed. The following statement:

                 strncpy(a, "black", 5);
gives the string in the array the new value "blackberry".

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值