[英]How do I convert a char * string into a pointer to pointer array and assign pointer values to each index?
I have a char * that is a long string and I want to create a pointer to a pointer(or pointer array). 我有一个char *,它是一个长字符串,我想创建一个指向指针(或指针数组)的指针。 The char ** is set with the correct memory allocated and I'm trying to parse each word from the from the original string into a char * and place it in the char **. char **设置了正确的内存分配,我试图将原始字符串中的每个单词解析为char *并将其放在char **中。
For example char * text = "fus roh dah char **newtext = (...size allocated)
So I'd want to have: 例如char * text = "fus roh dah char **newtext = (...size allocated)
所以我想拥有:
char * t1 = "fus", t2 = "roh", t3 = "dah";
newtext[0] = t1;
newtext[1] = t2;
newtext[2] = t3;
I've tried breaking the original up and making the whitespace into '\\0' but I'm still having trouble getting the char * allocated and placed into char** 我尝试将原始内容拆开并将空白设置为'\\ 0',但是仍然无法获取char *分配并放入char **
Try this char *newtext[n];
试试这个char *newtext[n];
. 。 Here n
is a constant and use this if n
is known beforehand. 这里n
是一个常数,如果n
是事先已知的,则使用它。
Otherwise char **newtext = malloc(n * sizeof *newtext);
否则char **newtext = malloc(n * sizeof *newtext);
here n
is a variable. 这里n
是一个变量。
Now you can assign char*
as in your example: 现在,您可以如示例中那样分配char*
:
newtext[0] = t1;
newtext[1] = t2;
newtext[2] = t3;
...
newtext[n-1] = ..;
Hope that helps. 希望能有所帮助。
Assuming that you know the number of words , it is trivial: 假设您知道单词的数量,这很简单:
char **newtext = malloc(3 * sizeof(char *)); // allocation for 3 char *
// Don't: char * pointing to non modifiable string litterals
// char * t1 = "fus", t2 = "roh", t3 = "dah";
char t1[] = "fus", t2[] = "roh", t3[] = "dah"; // create non const arrays
/* Alternatively
char text[] = "fus roh dah"; // ok non const char array
char *t1, *t2, *t3;
t1 = text;
text[3] = '\0';
t2 = text + 4;
texts[7] = '\0';
t3 = text[8];
*/
newtext[0] = t1;
newtext[1] = t2;
newtext[2] = t2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.