#include<string.h> #include<stdio.h> int main(void) { char input[16]="abc,d"; int i=0; char *p[2]; p[i]=strtok(input,",");

if(p[i])
 {
 i++;
    printf("%s\n",p[i-1]);}
   
p[i]=strtok(NULL,",");
if(p[i])
{
 i++;
    printf("%s\n",p[i-1]);}
return 0;

}以下是修复后的代码:

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

int main(void) {
    char input[16] = "abc,d";
    int i = 0;
    char *p[2];
    p[i] = strtok(input, ",");
   
    if (p[i]) {
        i++;
        printf("%s\n", p[i-1]);
    }
       
    p[i] = strtok(NULL, ",");
    if (p[i]) {
        i++;
        printf("%s\n", p[i-1]);
    }
    
    return 0;
}

修复的问题包括:

  1. 声明 char *p[i] 可能导致未定义行为,因为 i 的值还未被赋值。改为 char *p[2] 来声明 p 数组。
  2. 在使用 printf 打印 p 数组元素时,应该使用 p[i-1] 来打印上一个元素,因为 i 在打印之后会自增。
  3. strtok 调用之前,应该先将 i 的值设置为0。

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

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