1
该C程序将字符串“1 2 3 4 5 6 7 8 9 10”分成标记,将它们存储在buf
中,并打印buf
的内容。为什么此C程序无法正常工作?
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/* Fills an array with pointers to the tokens of the given string.
* string: A null-terminated char*
* buf: A buffer to be filled with pointers to each token.
*/
void get_tokens(char * string, char ** buf) {
char tmp[100];
strncpy(tmp, string, 100);
char * tok = strtok(tmp, " \n");
int i = 0;
while (tok != NULL) {
buf[i] = tok;
tok = strtok(NULL, " \n");
i++;
}
}
int main() {
char ** buf = malloc(10 * sizeof(char*));
char * string = "1 2 3 4 5 6 7 8 9 10";
get_tokens(string, buf);
int i;
for (i = 0; i < 10; i++) {
printf(" %s\n", buf[i]);
}
}
输出:
1
2
3
4
s�c8
�c8
8
9
10
为什么我的输出被错位?
的根本原因是'tmp'从'get_tokens'返回之后被淘汰的范围。 – Ctx
'char tmp [100];'是局部变量。该部分地址超出范围无效。 – BLUEPIXY
但是strtok返回的指针并不是指向tmp的指针,它们是由malloc – Jamie