【发布时间】:2016-02-22 22:58:18
【问题描述】:
此 C 程序将字符串“1 2 3 4 5 6 7 8 9 10”拆分为标记,将它们存储在buf 中,并打印buf 的内容。
#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返回后超出范围。 -
char tmp[100];是局部变量。该部分的地址超出范围无效。 -
但是strtok返回的指针不是指向tmp的指针,是malloc组成的独立字符串
-
“它们是用 malloc 制作的独立字符串”。真的吗?代码的哪一部分是这样做的?
char * tok = strtok(tmp, " \n"); buf[i] = tok;。tok指向tmp中的一个位置。 -
我想我现在明白了,谢谢。 strtok 的输入字符串被破坏的原因是 strtok 只是将分隔符替换为
\0并返回一个指向每个标记 within tmp 开头的指针。
标签: c arrays memory malloc declaration