[英]how to add a char* into char** in C
I have an array of char arrays in C (not C++). 我在C中有一个char数组(不是C ++)。 The type is char**. 类型为char **。 I know it's length, but the lengths of the elements are unknown. 我知道它的长度,但是元素的长度未知。 and I have another char* array. 我还有另一个char *数组。 Need to append this char* to my char**, as the last element. 需要将此字符*添加到我的字符**中,作为最后一个元素。
How about: 怎么样:
char **pointers;
char *p;
/* ... */
pointers[last] = p;
The one thing you need to get right is the value of last
and you can easily keep track of it as you add elements to pointers
. 您需要弄清的一件事是last
的值,并且在向pointers
添加元素时可以轻松地跟踪它。
A simple way to keep track of last
is to always say: 跟踪last
一种简单方法是始终说:
pointers[last++] = p;
Another way is to keep a copy and advance it: 另一种方法是保留副本并进行复制:
char **pts = pointers;
/* .. */
pts = p;
pts++;
char* arr1[]; char * arr1 []; //known length with some already filled elements //已知长度和一些已经填充的元素
each element of the above array is a pointer to character array. 上面数组的每个元素都是一个指向字符数组的指针。
char *new = "lastElem" // this is the string you have to append char * new =“ lastElem” //这是您必须附加的字符串
let us say, arr1 has n elements(each a string). 假设arr1有n个元素(每个字符串)。 Then, 然后,
arr1[++n] = new; arr1 [++ n] =新; // this should do it, provided space exists in arr1 and you already have the //character array 'new'. //如果arr1中存在空间并且您已经有//字符数组'new',则应该这样做。
Quite easy with realloc
: 使用realloc
非常容易:
char **array = ...;
array = realloc(array, sizeof(char*)*(LENGTH+1));
array[LENGTH] = last;
(I'm assuming you need to increase the size of array
, otherwise array[LENGTH-1] = last
is enough) (我假设您需要增加array
的大小,否则array[LENGTH-1] = last
就足够了)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.