我是 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;
}
感谢任何帮助!
最佳答案
第一个代码片段:
调试器不知道您在 p_array
中分配了多少空间,因此它不会显示数组的大小以及超过第一个元素的大小。顺便说一句,p_array
不是一个数组,而只是一个指向 int
的指针。
第二个代码片段:
代码对我来说看起来是正确的,但它是:
char polynom[] = "2x +5x^2 +8";
而不是
char[] polynom = "2x +5x^2 +8";
关于c - 在c中动态分配动态分配的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30039147/