我很想将此代码用作动态数组。不幸的是,我无法弄清楚为什么程序不使用分配的内存。可能是AddToArray
函数的参数有问题吗?
可以将此代码直接复制并粘贴到IDE中并进行编译,以查看输出。内存似乎已分配但未使用?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
float x;
float y;
} DATA;
int AddToArray (DATA item,
DATA **the_array,
int *num_elements,
int *num_allocated)
{
if(*num_elements == *num_allocated)
{ // Are more refs required?
// Feel free to change the initial number of refs
// and the rate at which refs are allocated.
if (*num_allocated == 0)
{
*num_allocated = 3; // Start off with 3 refs
}
else
{
*num_allocated *= 2;
}// Double the number of refs allocated
// Make the reallocation transactional by using a temporary variable first
void *_tmp = realloc(*the_array, (*num_allocated * sizeof(DATA)));
// If the reallocation didn't go so well, inform the user and bail out
if (!_tmp)
{
printf("ERROR: Couldn't realloc memory!\n");
return(-1);
}
// Things are looking good so far, so let's set the
*the_array = (DATA*)_tmp;
}
(*the_array)[*num_elements] = item;
*num_elements++;
return *num_elements;
}
int main()
{
DATA *the_array = NULL;
int num_elements = 0; // To keep track of the number of elements used
int num_allocated = 0; // This is essentially how large the array is
// Some data that we can play with
float numbers1[4] = {124.3,23423.4, 23.4, 5.3};
float numbers2[4] = { 42, 33, 15, 74 };
int i;
// Populate!
for (i = 0; i < 4; i++)
{
DATA temp;
temp.x = numbers1[i];
temp.y = numbers2[i];
if (AddToArray(temp, &the_array, &num_elements, &num_allocated) == -1)
return 1; // we'll want to bail out of the program.
}
for (i = 0; i < 4; i++)
{
printf("(x:%f,y:%f)\n", the_array[i].x, the_array[i].y);
}
printf("\n%d allocated, %d used\n", num_allocated, num_elements);
// Deallocate!
free(the_array);
// All done.
return 0;
}
答案 0 :(得分:3)
在您的代码中,您需要更改
*num_elements++;
到
(*num_elements)++;
因为没有明确的括号,++
优先于*
运算符。你想要的是增加存储在地址中的值,而不是相反。
检查运营商优先级here。
答案 1 :(得分:1)
试
(*num_elements)++;
在功能
AddToArray()
答案 2 :(得分:1)
代码中的错误是指针递增,而不是值。
..
(*the_array)[*num_elements] = item;
(*num_elements)++;
..
这是某种编程任务吗?这里的代码可以在很多方面得到改进。 这类问题有很多很好的算法,写得很好,优化得很好,我建议你在那个领域进行一些研究。