C语言字符串分割代码修复 - strtok函数使用解析
#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;
}
修复的问题包括:
- 声明
char *p[i]可能导致未定义行为,因为i的值还未被赋值。改为char *p[2]来声明p数组。 - 在使用
printf打印p数组元素时,应该使用p[i-1]来打印上一个元素,因为i在打印之后会自增。 - 在
strtok调用之前,应该先将i的值设置为0。
原文地址: https://www.cveoy.top/t/topic/pNBy 著作权归作者所有。请勿转载和采集!