c - 如何将 char * 字符串转换为指向指针数组的指针并为每个索引分配指针值?

标签 c pointers malloc c-strings pointer-to-pointer

我有一个 char * 是一个长字符串,我想创建一个指向指针(或指针数组)的指针。 char ** 设置为分配了正确的内存,我试图将每个单词从原始字符串解析为 char * 并将其放入 char **。

例如 char * text = "fus roh dah char **newtext = (...分配大小) 所以我想要:

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/

相关文章:

c - 在 SDL 中使用 gimp 导出的 .c/.h 图像

将输入字符串转换为 IP 地址格式

C:大字符串输入 --> 段错误

c - 为什么以下代码打印 1 作为输出?

c++ - 为什么我的复制构造函数在这种情况下只被调用两次?

C malloc 只为 int * 分配了 8 个字节

C - 取消分配整数列表

c - 为什么 (5+10)/2 是 7.0 而不是 7.5? C编程

delphi - Delphi AnsiString操作-PAnsiChar损坏了吗?

objective-c - 初始化 C 结构数组 - Objective C - OpenGLES