为什么在 Mac & 中使用 strtok_r 会产生不同的结果Ubuntu [英] Why is different result using strtok_r in Mac & Ubuntu
问题描述
我在练习 c Lang strtok_r().
这是我的代码.
I'm practice c Lang strtok_r().
Here is my code.
#include<stdio.h>
#include<string.h>
#include<unistd.h>
int main(int argc, char** argv){
char* ptr = NULL;
char* next[2] = {0};
char delimiter[4];
int now = 1;
strcpy(delimiter, " \t");
// check argc number
if(argc != 3){
printf("usage : ./test {string} {string}\n");
return -1;
}
ptr = strtok_r(argv[1], delimiter, &next[1]);
printf("ptr : %s, next : %s\n", ptr, next[1]);
ptr = strtok_r(argv[2], delimiter, &next[2]);
while((ptr = strtok_r(NULL, delimiter, &next[1])) != NULL){
printf("%d : %s, next : %s\n", ++now, ptr, next[1]);
}
return 0;
}
我认为代码结果将是
$ a.out "I'm test now" "Hello every"
ptr : i'm, next : test now
2 : test, next : now
3 : now, next : (null)
我的 mac 结果就是这样.
My mac result is that.
但我的 ubuntu20.04(Docker 镜像)不是.
这是在 Ubuntu 上执行的结果.
But my ubuntu20.04(Docker image) isn't.
Here is result of execute on Ubuntu.
$ a.out "i'm test now" "hello every"
ptr : i'm, next : test now
2 : test now, next :
为什么 Mac & 中的结果不同Ubuntu
Why result is different in Mac & ubuntu
推荐答案
关于:
char* next[2] = {0};
...
ptr = strtok_r(argv[1], delimiter, &next[1]);
printf("ptr : %s, next : %s\n", ptr, next[1]);
ptr = strtok_r(argv[2], delimiter, &next[2]);
while((ptr = strtok_r(NULL, delimiter, &next[1])) != NULL){
数组:next
有 2 个元素.因此,该数组的有效索引是 0 和 1.不是 1 和 2.
the array: next
has 2 elements. Therefore, the valid indexes into that array are 0 and 1. Not 1 and 2.
发布的代码访问超出了 next
数组的末尾.结果是未定义的行为.
The posted code is accessing beyond the end of the next
array. The result is Undefined Behavior.
注意:数组的有效索引为 0...(数组中的元素数 -1)
Note: the valid indexes into an array are 0...(number of elements in array -1)
这篇关于为什么在 Mac & 中使用 strtok_r 会产生不同的结果Ubuntu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!