【发布时间】:2010-09-15 05:43:39
【问题描述】:
我正在编写一个函数,它获取系统的路径环境变量,拆分每个路径,然后将一些其他额外字符连接到每个路径的末尾。
在我使用 strcat() 函数之前一切正常(参见下面的代码)。
char* prependPath( char* exeName )
{
char* path = getenv("PATH");
char* pathDeepCopy = (char *)malloc(strlen(path) + 1);
char* token[80];
int j, i=0; // used to iterate through array
strcpy(pathDeepCopy, path);
//parse and split
token[0] = strtok(pathDeepCopy, ":"); //get pointer to first token found and store in 0
//place in array
while(token[i]!= NULL) { //ensure a pointer was found
i++;
token[i] = strtok(NULL, ":"); //continue to tokenize the string
}
for(j = 0; j <= i-1; j++) {
strcat(token[j], "/");
//strcat(token[j], exeName);
printf("%s\n", token[j]); //print out all of the tokens
}
}
我的 shell 输出是这样的(我将“/which”连接到所有内容上):
...
/usr/local/applic/Maple/bin/which
which/which
/usr/local/applic/opnet/8.1.A.wdmguru/sys/unix/bin/which
which/which
Bus error (core dumped)
我想知道为什么strcat 显示一个新行,然后重复which/which。
我也想知道最后的Bus error (core dumped)。
有没有人在使用strcat() 时见过这个?
如果是这样,有人知道如何解决吗?
谢谢
【问题讨论】:
-
是我还是 SO 上有很多未注册的史蒂夫?
-
您的代码缺少一些“”符号:char pathDeepCopy = (char )malloc(strlen(path) + 1);字符令牌[80];
-
@bk1e:OP 确实输入了它们,但 SO 将它们解释为斜体格式。