如何将 char * 字符串转换为指向指针数组的指针并为每个索引分配指针值?
How do I convert a char * string into a pointer to pointer array and assign pointer values to each index?
我有一个 char * 是一个长字符串,我想创建一个指向指针(或指针数组)的指针。 char ** 设置为分配了正确的内存,我正在尝试将每个单词从原始字符串解析为 char * 并将其放入 char **。
例如
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;
我试过分解原始字符并将空格变成 '\0' 但我仍然无法分配 char * 并将其放入 char**
试试这个 char *newtext[n];
。这里 n
是一个常数,如果事先知道 n
就使用它。
否则char **newtext = malloc(n * sizeof *newtext);
这里n
是一个变量
现在您可以像示例中那样分配 char*
:
newtext[0] = t1;
newtext[1] = t2;
newtext[2] = t3;
...
newtext[n-1] = ..;
希望对您有所帮助。
假设您知道 个单词的数量,这是微不足道的:
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] = '[=10=]';
t2 = text + 4;
texts[7] = '[=10=]';
t3 = text[8];
*/
newtext[0] = t1;
newtext[1] = t2;
newtext[2] = t2;
我有一个 char * 是一个长字符串,我想创建一个指向指针(或指针数组)的指针。 char ** 设置为分配了正确的内存,我正在尝试将每个单词从原始字符串解析为 char * 并将其放入 char **。
例如
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;
我试过分解原始字符并将空格变成 '\0' 但我仍然无法分配 char * 并将其放入 char**
试试这个 char *newtext[n];
。这里 n
是一个常数,如果事先知道 n
就使用它。
否则char **newtext = malloc(n * sizeof *newtext);
这里n
是一个变量
现在您可以像示例中那样分配 char*
:
newtext[0] = t1;
newtext[1] = t2;
newtext[2] = t3;
...
newtext[n-1] = ..;
希望对您有所帮助。
假设您知道 个单词的数量,这是微不足道的:
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] = '[=10=]';
t2 = text + 4;
texts[7] = '[=10=]';
t3 = text[8];
*/
newtext[0] = t1;
newtext[1] = t2;
newtext[2] = t2;