#include 'stdio.h' int main(){ char s[32]; *s = 'computer'; for (int i = 0; *s != '\0'; i+=2) { printf('%c ',s[i]); } } 为什么错了?

代码中的第二行应该是 s[0] = 'c'; 而不是 *s = 'computer';。原因是:

  1. s 是一个字符数组,需要使用下标来访问其中的每一个字符,而 *s 是数组的第一个元素,它是一个字符类型,不能直接赋值为一个字符串。
  2. 字符串常量应该使用双引号括起来,而单引号表示一个字符,因此应该写成 s[0] = 'c';。

修改后的代码如下:

#include 'stdio.h'
int main(){
    char s[32];
    s[0] = 'c';
    s[1] = 'o';
    s[2] = 'm';
    s[3] = 'p';
    s[4] = 'u';
    s[5] = 't';
    s[6] = 'e';
    s[7] = 'r';
    s[8] = '\0';
    for (int i = 0; s[i] != '\0'; i+=2) {
        printf('%c ',s[i]);
    }
    return 0;
}

输出结果为:c m u e。

C语言字符数组赋值错误分析及修正

原文地址: https://www.cveoy.top/t/topic/npdX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录