将两个指针数组合并到C语言中的第三个指针数组中 [英] Merge two arrays of pointers into a third array of pointers in C

查看:556
本文介绍了将两个指针数组合并到C语言中的第三个指针数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C编写程序,但找不到执行以下操作的方法.我有两个以NULL终止的字符串指针数组,即

I'm writing a program in C and I can't find out how to do the following. I have two NULL terminated arrays of pointers to strings, namely

char *tokens1[size1]
char *tokens2[size2]

我想将它们合并为指向字符串的第三个指针数组,即

I want to merge them into a third array of pointers to strings, namely

char **tokens;

我尝试了以下操作,但不起作用:

I've tried the following but it doesn't work:

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:

You are copying pointer values, not strings, so you need to use memcpy instead of 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语言中的第三个指针数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆