gpt4 book ai didi

c - 想知道此声明与代码中的注释相比有什么问题吗? - 初学者在这里

转载 作者:行者123 更新时间:2023-12-05 02:28:57 25 4
gpt4 key购买 nike

// Online C compiler to run C program online

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

int main()
{
char *s1 = "Hello"; /* Code doesn't work with this declaration instead works with char s1[] = "Hello"; */

char *s2 = "world";

strcpy(s1,s2);

printf("copied is %s into %s",s1,s2);

return 0;
}

char *s1 和 char s1[] 声明不一样吗?

最佳答案

Aren't char *s1 and char s1[] declarations same ?

声明

char *s1 = "Hello";

声明一个指向字符串文字的指针。您不能更改字符串文字。任何更改字符串文字的尝试,例如

strcpy(s1,s2);

导致未定义的行为。

这个声明

char s1[] = "Hello";

声明一个字符数组,其元素由字符串文字的元素初始化。上面的声明等同于

char s1[] = { 'H', 'e', 'l', 'l', 'o', '\0' };

您可以更改字符数组,因为它没有声明为常量数组。

所以 strcpy 的调用对于数组是正确的

strcpy(s1,s2);

你也可以这样写

char s1[] = "Hello";
char *p = s1;
//...
strcpy(p,s2);

因为在这种情况下指针 p 不指向字符串文字。它指向非常量字符数组s1

以及printf调用中的消息

printf("copied is %s into %s",s1,s2);

错了。其实这个电话

strcpy(s1,s2);

将字符从 s2 复制到 s1

关于c - 想知道此声明与代码中的注释相比有什么问题吗? - 初学者在这里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72411521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com