简体   繁体   English

在c中动态分配动态分配的字符串数组

[英]dynamically allocating an array of dynamically allocated strings in c

I'm new to C and I'm having a problem with saving dynamically allocated strings in dynamically allocated array. 我是C语言的新手,将动态分配的字符串保存在动态分配的数组中时遇到问题。 I tried to look at a simple example: 我试图看一个简单的例子:

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;
}

however, when I'm debugging it in visual studio it seems like I don't have an array with 3 slots, in p_array it shows me only {1} . 但是,当我在Visual Studio中调试它时,似乎没有3个插槽的数组,而在p_array中,它仅显示{1}。 the same problem happened to me with my actual code that I'm trying to write: in the actual code, I get from the user a polynomial in the running time, and need to put in an array each term of the polynomial in a different cell. 我尝试编写的实际代码也发生了同样的问题:在实际代码中,我在运行时从用户那里获得了一个多项式,并且需要将多项式的每个项放在不同的数组中细胞。 I don't know the polynomial length so I need to allocate the array dynamically. 我不知道多项式的长度,所以我需要动态分配数组。 in this example I wrote a constant string as the polynomial for your help. 在此示例中,我写了一个常量字符串作为多项式来帮助您。 the I'm trying to enter to the array the terms but as the other example, in the debugging I only see at the end the array {2x} 我正在尝试将术语输入到数组中,但作为另一个示例,在调试中,我仅在数组的最后看到{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;
}

I appreciate any help! 感谢您的帮助!

First code snippet: 第一个代码段:

The debugger doesn't know how much you have allocated in p_array and therefore it doesn't display the size of the array and more than the first element. 调试器不知道您在p_array分配了p_array ,因此它不显示数组的大小,也不显示第一个元素。 BTW p_array is not an array but just a pointer to int . 顺便说一句p_array不是数组,而只是一个指向int的指针。

Second code snippet: 第二个代码段:

The code looks correct to me but it's: 该代码对我来说似乎正确,但它是:

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

and not 并不是

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

When allocating the array of pointers you need to make sure you are allocating enough space. 分配指针数组时,需要确保分配了足够的空间。

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

Will most likely not allocate all the memory needed. 将很可能不会分配所有需要的内存。

Use: 采用:

polyTerms = malloc(sizeof term * sizeof polynom);

Also, you may want to look into using strdup() in your code that allocates and copies into your array. 另外,您可能想研究在代码中使用strdup()分配并复制到数组中的情况。

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

Can become: 可以变成:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM