【问题标题】:dynamically allocating an array of dynamically allocated strings in c在c中动态分配一个动态分配的字符串数组
【发布时间】:2015-07-14 08:54:18
【问题描述】:

我是 C 新手,在将动态分配的字符串保存在动态分配的数组中时遇到问题。 我试着看一个简单的例子:

int*    p_array;

// call malloc to allocate that appropriate number of bytes for the array

p_array = malloc(sizeof(int) * 3);      // allocate 3 ints


// use [] notation to access array buckets
for (int i = 0; i < 3; i++) {
    p_array[i] = 1;
}

但是,当我在 Visual Studio 中调试它时,似乎我没有一个带有 3 个插槽的数组,在 p_array 中它只显示 {1} 。我正在尝试编写的实际代码也发生了同样的问题:在实际代码中,我在运行时从用户那里得到一个多项式,并且需要将多项式的每个项放入一个数组中细胞。我不知道多项式长度,所以我需要动态分配数组。在这个例子中,我写了一个常量字符串作为多项式来为您提供帮助。我正在尝试将术语输入到数组中,但作为另一个示例,在调试中我只在末尾看到数组 {2x}

char[] polynom = "2x +5x^2 +8";
char* term;
char** polyTerms;
int i=0;
term = strtok(polynom, " ");
polyTerms = (char**)malloc(3* sizeof(polynom));


while (term != NULL)
{

    polyTerms[i] = (char *)calloc(strlen(term) + 1, sizeof(char));
    strcpy(polyTerms[i], term);
    term = strtok(NULL, " ");

    i += 1;
}

感谢您的帮助!

【问题讨论】:

  • char[] polynom = "2x +5x^2 +8"; --> char polynom[] = "2x +5x^2 +8";
  • 在分配指针数组时,您需要确保分配了足够的空间。将polyTerms = (char**)malloc(3* sizeof(polynom)); 替换为polyTerms = malloc(sizeof term * sizeof polynom);

标签: c pointers memory-management dynamic-memory-allocation


【解决方案1】:

第一个代码sn-p:

调试器不知道您在p_array 中分配了多少,因此它不会显示数组的大小,也不会显示第一个元素的大小。 BTW p_array 不是一个数组,而只是一个指向 int 的指针。

第二个代码sn-p:

代码在我看来是正确的,但它是:

char polynom[] = "2x +5x^2 +8";    

而不是

char[] polynom = "2x +5x^2 +8";

【讨论】:

    【解决方案2】:

    在分配指针数组时,您需要确保分配了足够的空间。

    (char**)malloc(3* sizeof(polynom));

    很可能不会分配所有需要的内存。

    用途:

    polyTerms = malloc(sizeof term * sizeof polynom);

    此外,您可能希望在代码中使用strdup() 来分配和复制到您的数组中。

    polyTerms[i] = (char *)calloc(strlen(term) + 1, sizeof(char));
    strcpy(polyTerms[i], term);
    

    可以变成:

    polyTerms[i] = _strdup(term); // VS2013 version of POSIX strdup()
    

    【讨论】:

    • 正如迈克尔所提到的,您需要正确声明您的数组。 char polynom[] = "2x +5x^2 +8";
    • 另请注意sizeof(char) 始终为 1。
    猜你喜欢
    • 2011-10-21
    • 2013-03-09
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    相关资源
    最近更新 更多