我正在用 C 编写程序,但我不知道如何执行以下操作。我有两个以 NULL 结尾的指向字符串的指针数组,即
char *tokens1[size1]
char *tokens2[size2]
我想将它们合并成第三个字符串指针数组,即
char **tokens;
我已经尝试了以下但它不起作用:
char *tokens1[size1]
char *tokens2[size2]
char **tokens;
/* code to fill the *tokens1[] and *tokens2[] arrays with string values */
tokens = (char*) malloc(size1+size2+1);
strcpy(tokens, tokens1);
strcat(tokens, tokens2);
你能帮帮我吗?
最佳答案
您正在复制指针值,而不是字符串,因此您需要使用 memcpy
而不是 strcpy
/strcat
:
int i, j;
/* Find the current size of tokens1 and tokens 2 */
for (i=0; tokens1[i] != NULL; i++)
;
for (j=0; tokens2[j] != NULL; j++)
;
/* Allocate enough memory to hold the result */
tokens = calloc(i + j + 1, sizeof(char*));
/* Copy the arrays */
memcpy(tokens, tokens1, i * sizeof(char*));
memcpy(tokens + i, tokens2, j * sizeof(char*));
/* Since we used calloc, the new array is initialized with NULL:s. Otherwise we would have to NULL-terminate it like so: */
tokens[i+j] = NULL;
关于c - 将两个指针数组合并为 C 中的第三个指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13123844/