[英]Dynamic array allocated, but cannot use it
我想將此代碼用作動態數組。 不幸的是,我無法弄清楚為什么程序不使用分配的內存。 可能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;
}
在您的代碼中,您需要進行更改
*num_elements++;
至
(*num_elements)++;
因為在沒有顯式括號的情況下, ++
優先級高於*
運算符。 您想要的是增加存儲在地址中的值 ,而不是相反。
在此處檢查運算符的優先級。
嘗試
(*num_elements)++;
在功能上
AddToArray()
代碼中的錯誤是指針增加了,而不是值增加了。
..
(*the_array)[*num_elements] = item;
(*num_elements)++;
..
這是某種編程任務嗎? 這里的代碼可以在許多方面進行改進。 有很多很好的算法可以很好地解決此類問題,我建議您對該領域進行一些研究。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.