【发布时间】: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