char *str="STRING" 之间的区别和字符 str[] = “字符串"? [英] Difference between char *str="STRING" and char str[] = "STRING"?

查看:36
本文介绍了char *str="STRING" 之间的区别和字符 str[] = “字符串"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写一个简单的函数以从字符串中删除特定字符时,我遇到了这个奇怪的问题:

While coding a simple function to remove a particular character from a string, I fell on this strange issue:

void str_remove_chars( char *str, char to_remove)
{
    if(str && to_remove)
    {
       char *ptr = str;
       char *cur = str;
       while(*ptr != '\0')
       {
           if(*ptr != to_remove)
           {
               if(ptr != cur)
               {
                   cur[0] = ptr[0];
               }
               cur++;
           }
           ptr++;
       }
       cur[0] = '\0';
    }
}
int main()
{
    setbuf(stdout, NULL);
    {
        char test[] = "string test"; // stack allocation?
        printf("Test: %s\n", test);
        str_remove_chars(test, ' '); // works
        printf("After: %s\n",test);
    }
    {
        char *test = "string test";  // non-writable?
        printf("Test: %s\n", test);
        str_remove_chars(test, ' '); // crash!!
        printf("After: %s\n",test);
    }

    return 0;
}

我不明白的是为什么第二个测试失败了?对我来说,第一个符号 char *ptr = "string"; 等价于这个:char ptr[] = "string";.

What I don't get is why the second test fails? To me it looks like the first notation char *ptr = "string"; is equivalent to this one: char ptr[] = "string";.

不是吗?

推荐答案

这两个声明不一样.

char ptr[] = "string"; 声明一个大小为 7 的字符数组,并用字符
s 对其进行初始化,t,r,i,n,g\0.您被允许修改这个数组的内容.

char ptr[] = "string"; declares a char array of size 7 and initializes it with the characters
s ,t,r,i,n,g and \0. You are allowed to modify the contents of this array.

char *ptr = "string";ptr 声明为一个字符指针,并使用 字符串文字 " 的地址对其进行初始化string"只读.修改字符串文字是一种未定义行为.您所看到的(段错误)是未定义行为的一种表现.

char *ptr = "string"; declares ptr as a char pointer and initializes it with address of string literal "string" which is read-only. Modifying a string literal is an undefined behavior. What you saw(seg fault) is one manifestation of the undefined behavior.

这篇关于char *str="STRING" 之间的区别和字符 str[] = “字符串"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆