C语言 想知道这个声明与代码中的注释相反是什么问题?-我是新手


// 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[]声明不一样吗?

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

宣言

char *s1 = "Hello";

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

strcpy(s1,s2);

导致未定义的行为。

这项宣言

char s1[] = "Hello";

声明一个字符数组元素,其中的元素由字符串字面值的元素初始化。上面的声明相当于

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

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

对于数组

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

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

char *s1 = "Hello";

s1声明为指针——它存储的只是字符串字面值"Hello"地址:

+–––+
s1: |   | ––––––––––+
+–––+           |
...            |
+–––+           |
|'H'| <–––––––––+
+–––+
|'e'|
+–––+
|'l'|
+–––+
|'l'|
+–––+
|'o'|
+–––+
| 0 |
+–––+

试图修改字符串文字内容的行为(例如strcpy(s1,s2);)是undefined-您的代码可能会彻底崩溃,或者它可能只是无法更新字符串,或者它可能按预期工作。

宣言

char s1[] = "Hello";

分配一个足够大的char数组来存储字符串"Hello",并用该字符串初始化它:

+–––+  
s1: |'H'|
+–––+
|'e'|
+–––+
|'l'|
+–––+
|'l'|
+–––+
|'o'|
+–––+
| 0 |
+–––+

这是一个可以修改的实际数组。它不能存储任何长度超过"Hello"的字符串,但除此之外,您可以将其修改为您的核心内容。

最新更新