Quantcast
Channel: LabWindows/CVI topics
Viewing all articles
Browse latest Browse all 5340

How to dynamically allocate memory for a structure with an unknown number of elements?

$
0
0

I need to open a file and read in X number of analog input channels that my program will log.  I have gotten by in the past with the following allocation:

 

static	struct	DAQChannel 	*DAQAIChannels[100];  

DAQAIChannels[numAIChannels] = (struct DAQChannel*) malloc(sizeof(struct DAQChannel)); 

The trouble with this is that, if I don't allocate memory for all 100 channels, I get an error when I try to free all of the memory like this because some of the memory hasn't been allocated:

 

free(DAQAIChannels);

How should I use pointers such that I can allocate and free memory dynamically for an unknown number of AI channels?  I should be a little more clear that, as I read line by line from the file, I create a new index in the structure array so the number of channels is not known until the last AI channel line is read.

 

Thank you!


Viewing all articles
Browse latest Browse all 5340

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>