加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C中的字符串指针可以直接分配字符串文字吗?

发布时间:2020-12-16 10:13:53 所属栏目:百科 来源:网络整理
导读:以下程序运行正常,我很惊讶为什么: #include stdio.h#include stdlib.h#include string.h#include unistd.hvoid xyz(char **value){ // *value = strdup("abc"); *value = "abc"; // -- ??????????}int main(void){ char *s1; xyz(s1); printf("s1 : %s n"
以下程序运行正常,我很惊讶为什么:

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

void xyz(char **value)
{
        // *value = strdup("abc");
        *value = "abc"; // <-- ??????????
}

int main(void)
{
        char *s1;

        xyz(&s1);

        printf("s1 : %s n",s1);
}

输出:

s1 : abc

我的理解是我必须使用strdup()函数为C中的字符串分配内存,而我没有分配内存.但是在这种情况下,只需使用“”分配字符串值,程序似乎工作正常,任何人都可以解释一下吗?

解决方法

以太字符串中不存在字符串文字.它们驻留在程序存储器中并具有地址.

因此,您可以将该地址分配给指针.程序的行为定义得很好,只要你不尝试通过指针修改文字,就不会发生任何不好的事情.

因此,最好通过const正确使编译器为您工作.希望尽可能将指针类型标记为const,并且编译器将反对修改尝试.

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

void xyz(char const **value)
{
        *value = "abc";
}

int main(void)
{
        char const *s1;

        xyz(&s1);

        printf("s1 : %s n",s1);
        s1[0] = 'a'; << Error on this line
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读