c - c中带有malloc的字符串数组的数组

标签 c linux gcc

你能告诉我我做错了什么吗?打印 printf("%s\n",text[0]);

时我没有得到文本

我创建了 char **text;malloc 了所有指针。

#include<stdio.h>
#include<string.h>
#include<stdlib.h>


char **text;

int main()
{
    int i; 
    text = malloc(20000);


    for(i=0; i < 20000; i++) {
        text[i] = malloc(4);

        memcpy(text[i], "test",4);
    }
    printf("%s\n",text[0]);
    printf("%s\n",text[1]);
}

最佳答案

我相信您正在寻找这样的东西:

int numElements = 20000, i;
// Allocate an array of char pointers
text = malloc(numElements * sizeof( char *)); 

for( i = 0; i < numElements; i++) {
    // 4 for the length of the string "test", plus one additional for \0 (NULL byte)
    text[i] = malloc( (4 + 1) * sizeof( char));
    memcpy( text[i], "test\0", 5);
}

这是一个 online demo显示它正在工作,因为它会产生输出:

test
test

关于c - c中带有malloc的字符串数组的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16390117/

相关文章:

linux - 如何使用 Unix CAT 和查找插入新行

linux - xterm-color 和 xterm-256color 有什么区别?

c - gcc 是否支持嵌入式汇编语法?

gcc - 学习GNU GCC编译优化实现

c - ANSI C 中的复合语句( block )是否被括号表达式包围?

c++ - 为什么我在 C 库中看到 THROW?

c - 如何处理二进制文件格式的可移植性问题

c - 有没有办法让 GCC/Clang 知道 C 中的继承?

c - 带间隙的随机数

c++ - 为什么一般程序一般都是从0x8000开始?