是否可以连接并添加一个指针数组到另一个指针数组的一个索引中。我试图将字符串放在* token指针内,并使其在命令指针数组的第一个索引内成为一个字符串,依此类推
cmd = strtok(str, " ");
while(n < 5 && (act_token = strtok(NULL, " ")))
{
token[n] = act_token;
n++;
}
token[n] = NULL;
/* Below is where I'm trying to add all the elements of the token array into one index of the comands array */
while( z < len ){
comands[b] = token[z];
z++;
}
b++;
}
答案 0 :(得分:2)
我感到你很痛苦。字符串处理在C语言中非常糟糕,在C ++中几乎同样糟糕。 但是,一旦编写了函数,您所要做的就是调用它...
char *GetStringFromStringArray(const char**sourceStrings, size_t nCount)
{
char *destString = NULL;
size_t destLength = 1; //start with room for null-terminator
if (nCount == 0)
return destString;
for (size_t i = 0; i < nCount; i++)
destLength += strlen(sourceStrings[i]);
destString = (char*)malloc(destLength);
strcpy(destString, sourceStrings[0]);
for (size_t i = 1; i < nCount; i++)
strcat(destString, sourceStrings[i]);
return destString;
}
int main()
{
char *tokens[10] = { "bob", "jim", "hank" };
char *destStrings[2];
destStrings[0] = GetStringFromStringArray((const char**)tokens, 2);
destStrings[1] = GetStringFromStringArray((const char**)&tokens[1], 2);
free(destStrings[0]);
free(destStrings[1]);
}
顺便说一下,我初始化tokens
的方式还不行。纯粹是简单的例子。
答案 1 :(得分:2)
为避免由于循环级联而导致的O(n * n)复杂性,在@zzxyz否则为好答案,请考虑复制到累积目标的末尾。
char *concat_alloc(const char *token[], size_t n) {
size_t sum = 1;
for (size_t i = 0; i < n; i++) {
size_t len = strlen(token[i]);
sum += len;
if (sum < len) {
return NULL; // Too long
}
}
char *dest = malloc(sum);
if (dest) {
char *p = dest;
for (size_t i = 0; i < n; i++) {
size_t len = strlen(token[i]);
memcpy(p, token[i], len);
p += len; // advance to the end
}
*p = '\0';
}
return dest;
}