为什么动态数组包含 null 而不是实际的字符串

Why does dynamic array contain null instead of actual string

首先,我不知道堆内存是否以连续的方式使用,使用 do...while 循环,其次,当我尝试打印存储在数组中的字符串时,我得到的是 NULL 值实际字符串

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

#pragma warning(disable : 4996)

int main() {
    int counter = 0;
    char** tab;
    do {
        tab = (char**)malloc(3 * sizeof(char));
        tab[counter] = (char*)malloc(256 * sizeof(char));
        fgets(*(tab + counter), 256, stdin);
        ++counter;
    } while (counter < 3);
    printf("%s", tab[0]);
    
}

根据代码,tab 应该是一个大小为 3 的字符串指针数组。但是至少有2个错误

  1. 你在每次循环迭代中分配一个新的数组副本
  2. 你只为 3 个字符分配 space,而不是 3 个指针。
    do {
        tab = (char**)malloc(3 * sizeof(char));

因此,您的代码应如下所示:

tab = malloc(3 * sizeof(char*));
do {
...

在 'c' 中不需要转换为 char**

下一行可以:

        tab[counter] = (char*)malloc(256 * sizeof(char));

这一行也可以,前提是您熟悉指针运算。

        fgets(*(tab + counter), 256, stdin);

不过可以换个方式表达,可读性更好一些

        fgets(tab[counter], 256, stdin);

这是工作代码:

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

#pragma warning(disable : 4996)

int main() {
    int counter = 0;
    char** tab = malloc(3 * sizeof(char*));
    do {
        tab[counter] = malloc(256 * sizeof(char));
        fgets(tab[counter], 256, stdin);
        ++counter;
    } while (counter < 3);
    printf("%s", tab[0]);
}