c - *s++ 中发生了什么?

标签 c

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

#define bool int
#define true 1
#define false 0

static bool is_digit(char c){
    return c > 47 && c < 58;
}

static bool is_all_digit(char *s){
    while(s){
        if(is_digit(*s++)){
            continue;
        }
        return false;
    }
    return true;
}


int main(){
    char *s = "123456";
    int i;
    printf("len = %d\n", strlen(s));
    for(i = 0; i<strlen(s); ++i){
        printf("%c : %s\n", *s, is_digit(*s++)? "true" : "false");
        //printf("%c : %s\n", s[i], is_digit(s[i])? "true" : "false");
    }
    return 0;
}

我想实现评论部分的功能。 但结果如下:enter image description here

以3结尾,4~6消失。 我的运行环境是win10 gcc 6.3.0

最佳答案

这存在很多问题。

  1. printf使用了错误的格式字符串。 Use %zu for a size_t, not %d

  2. 您的 printf 具有未定义的行为,因为同一表达式中有 *s*s++,它们之间没有 sequence point .

  3. 您在循环的每次迭代中重新计算 strlen(s),并且该值不断下降,因为您不断增加 s。在开始之前,我会将 strlen(s) 缓存到名为 n (或类似变量)的变量中,因为 n 不会改变。

我的编译器警告我除了第三个错误之外的所有错误。

该程序有效:

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

#define bool int
#define true 1
#define false 0

static bool is_digit(char c){
    return c > 47 && c < 58;
}


int main(){
    const char *s = "123456";
    size_t i;
    const size_t n = strlen(s);
    printf("len = %zu\n", n);
    for(i = 0; i<n; ++i){
        printf("%c : %s\n", *s, is_digit(*s)? "true" : "false");
        s++;
    }
    return 0;
}

(live demo)

您也可以完全跳过 strlen 并仅查找空终止符:

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

#define bool int
#define true 1
#define false 0

static bool is_digit(char c){
    return c > 47 && c < 58;
}


int main(){
    const char *s = "123456";
    while (*s) {
        printf("%c : %s\n", *s, is_digit(*s)? "true" : "false");
        s++;
    }
    return 0;
}

(live demo)

关于c - *s++ 中发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54959809/

相关文章:

C++ 删除管理员权限

java - 将 Java 套接字文件描述符传递给 C 二进制文件的最有效方法

c - 我有一个数组,我想将它传递给一个函数,然后从该函数修改它,我该怎么做?

c - avr-gcc 编译器优化了全局变量

c - 为什么 XLoadQueryFont 不能识别名称 8x13

c - C 中带有套接字的 POSIX 线程

c - 如何为 gcc 编写自己的代码生成器后端?

c - 如果有人正在等待共享信号量,如何检查 C Posix 线程?

c - 为什么我的程序在尝试打印字符指针时崩溃

CUDA 的 cudaMemcpyToSymbol() 抛出 "invalid argument"错误