【发布时间】:2012-05-03 05:26:28
【问题描述】:
我编写了以下程序来解析多个目录名称的路径
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *
tokenizer(char *path, char **name){
char s[300];
char *buffer;
memcpy(s, path, strlen(path)+1);
printf("%s\n",s); // PROBLEM
int i=0;
while(s[i] == '/'){
i++;
}
if (i == strlen(path)){
return NULL;
}
*name = strtok_r(s, "/", &buffer);
return buffer;
}
int main(void){
char str[300];
char *token, *p;
scanf("%s",str);
p = tokenizer(str, &token);
if (p != NULL)
printf("%s\n",token);
else
printf("Nothing left\n");
while((p=tokenizer(p, &token)) != NULL){
printf("%s\n",token);
}
}
上述程序的输出
Input: a/b/c
Output: a/b/c
a/b/c
a
b/c
b
c
c
如果我评论标有问题的行
Input: a/b/c
Output: Some garbage value
有人能解释一下这种奇怪行为的原因吗?
注意:
我已经意识到s 是一个堆栈分配变量,它在函数main() 中不再存在,但是为什么当我使用printf() 时程序可以工作?
【问题讨论】:
-
如果我编译你的程序,我会在最底部的
while行中收到警告。最好先调查一下。 -
@MrLister 我在编译程序时没有收到任何警告。您为 gcc 编译器指定了哪些选项?
-
为什么是 memcpy 而不是 strcpy? (无论如何你都依赖 strlen)
-
@gibraltar gcc 4.3 without options给了我
test.c:31: warning: passing argument 2 of ‘tokenizer’ from incompatible pointer type -
@MrLister 我已经纠正了错误。很抱歉。