我有一个字符*是一个长字符串,我想创建一个指向指针(或指针数组)的指针。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 = 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;

关于c - 如何将char *字符串转换为指向指针数组的指针,并将指针值分配给每个索引?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48314620/

10-16 20:23