【问题标题】:How to initialize rows of 2D array of strings in C如何在C中初始化二维字符串数组的行
【发布时间】:2015-09-29 02:27:27
【问题描述】:

我想使用指针将字符串存储在二维数组中,但我不知道该怎么做。我见过的示例仅使用整数数组或使用方括号 [] 分配固定大小的内存。所以我正在尝试初始化我的二维字符串数组,这就是我所拥有的:

char ** stringArr = (char**)malloc(/*I don't know what goes here*/);
for(i = 0; i < rows; i++)
    stringArr[i] = (char*)malloc(cols *sizeof(char));

您可以看到我第一次调用 malloc 的参数,如果我想要确切的 x 行数,我不知道该放什么,其中每行存储一串字符。任何帮助将不胜感激!

【问题讨论】:

    标签: c arrays memory-management char


    【解决方案1】:

    这样做,因为您分配了一些指针:

    malloc(rows * sizeof(char*))
    

    【讨论】:

      【解决方案2】:

      你会想要使用行数。

      char ** stringArr = malloc(rows * sizeof(char*));
      

      另外,不要对 malloc() 调用的返回值进行类型转换。

      【讨论】:

      • 感谢您的回复,但为什么我不应该键入 malloc()?甚至 cplusplus.com 也会在 malloc() 的参考页面中对其进行类型转换。
      • @Ghost_Stark 这是该主题的受保护链接!希望它能让事情更清楚:stackoverflow.com/questions/605845/…
      【解决方案3】:

      使用sizeof *ptr * N

      请注意此方法如何使用正确的类型,即使 stringArrchar ** stringArrint ** stringArr

      stringArr = malloc(sizeof *stringArr * rows);
      for(i = 0; i < rows; i++)
          stringArr[i] = malloc(sizeof *(stringArr[i]) * cols);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-04
        • 2011-09-29
        • 1970-01-01
        • 2014-05-14
        • 2016-11-12
        • 1970-01-01
        • 2014-12-08
        相关资源
        最近更新 更多