c - 在字符串上使用指针

标签 c c-strings char-pointer

我真的很困惑在字符串上使用指针。 感觉他们遵守不同的规则。 考虑以下代码

  1. char *ptr = "apple";// perfectly valid here not when declaring afterwards like next
    
    ptr = "apple"; // shouldn't it be *ptr = "apple"
    
  2. printf() 的行为也不同 -

    printf("%s", ptr) // Why should I send  the address instead of the value
    
  3. 另外我在一本书中看到了下面的代码

    char str[]="Quest";
    char *p="Quest";
    
    str++; // error, constant pointer can't change
    
    *str='Z'; // works, because pointer is not constant
    
    p++; // works, because pointer is not constant
    
    *p = 'M'; // error, because string is constant
    

我不明白这是什么意思

请帮忙,我在别处找不到任何信息

最佳答案

char *ptr;
ptr = "apple"; // shouldn't it be *ptr =      "apple"

不,因为 *ptr 将是一个 char。所以,你可以写 *ptr = 'a' 但你不能按照你的建议写。

printf("%s", ptr) // Why should I send  the address instead of the value

因为 C 中的字符串是以零结尾的字符序列 (char) 的地址(空字符又名 \x0)。

char str[] = "Quest";
char *p = "Quest";

str++; // error, constant pointer can't change

不,指针可以完美改变,但这里,str 是一个数组(与指针略有不同)。但是,因此,它不能处理指针运算。

*str='Z'; // works, because pointer is not constant

不,它可以工作,因为 *str 应该是 char

p++; // works, because pointer is not constant

不,它起作用是因为这次它是一个指针(不是数组)。

*p = 'M'; // error, because string is constant

和上面一样,这又是一个char,所以它能工作是因为它是正确的类型而不是因为字符串是“常量”。而且,正如 Michael Walz 在评论中所述,即使它可以编译,它也会在运行时产生未定义的行为(很可能是 segfault 崩溃),因为规范没有说明字符串是否指向by *p 是只读的还是不是(然而,似乎大多数现代编译器实现决定将其设为只读)。这可能会产生 segfault

有关详细信息,请参阅 this SO question .

关于c - 在字符串上使用指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46057088/

相关文章:

c - 如何在 Windows 控制台中使用英语、俄语和西类牙语

c - 重新分配后打印字符串数组时遇到问题?

c - 参数少于指定的 sscanf?

c - C 中字符串的 printf 的意外输出

c++ - 空 char* 成功转换为有效的 unsigned int64 游戏 ID??如何?

c - 为什么 int (*p)[] 不能用作 C 函数的参数?

c - C语言系统函数——从CodeBlocks(C)程序创建用户

c - 赋值给数组类型为 ch= ch+(s[i]) 的表达式;

c++ - 字符*str;海峡 ="HELLO";在不为字符串分配任何内存的情况下如何工作?

c - 如何在 C 中将 void 指针转换为结构?