"Variable" Variablenames in C
I think what I am looking for is actually not possible in C, but maybe some has an idea how to work around it:
I need to process some input data. This data is given in an int with gives the number of data and a number of strings (i.e. char *) which hold the actual data. These strings are named data_0 ... data_n:
int n = 42; // the number of strings
char *data_0 = "some input1";
char *data_1 = "some input2";
....
char *data_41 = "the last input data";
So this is how I get the data. The question now is: How can I process it? My goal is to store them in a big array. Initializing this array is of course simple, I just need an array of n char-Pointer which I get with malloc. But then I want to assign these strings into the array. And this is the point where I'm stuck. I need to开发者_如何学JAVA assign them dynamically, as I do not know the size before. Something like:
for(i = 0; i < n; i++)
datastorage[i] = data_i;
So I mean accessing the variablename dynamically. I hope you understand what I mean :) Thank you.
Make it an array in the first place! There is absolutely no point in having 42 separate variables if you have to access them as an array! BTW, in C, variable names are not available at run time, they are simply lost after compilation, so forget about dynamically accessing variables by name.
int n = 42; // the number of strings
char *data[42];
data[0] = "some input1";
data[1] = "some input2";
....
data[41] = "the last input data";
for(i = 0; i < n; i++)
datastorage[i] = data[i];
There is no straightforward way to do this in C because the whole point of arrays is precisely to get rid of the need to do something like this. Traditionally, one uses arrays so that you can reference multiple different variables by their index without needing a unique name for each of those variables.
I find it odd that you would be getting input to your program as a C source file with one variable per line like this. If you're generating this C file, then you should instead generate it to use arrays, obviating the need for the corrective code you're asking for. If someone else is giving you C code like this, then ask them to change it to use arrays; there's no reason you should have to inconvenience yourself like this and the change should be very simple to make on your own.
I'm not 100% sure what you're trying to do to be honest...
From what I can see you want to eventually put all of these elements into an array.
So why not simply use an array of 42 elements and assign it based on what you can parse from the key.
ie: data_1, replace data_, leaves you with 1, datarray[atoi(1)] = your char pointer.
Does that sound right?
You could also make objects (structs in C...) and dynamically place them into another, more dynamic datastructure.
精彩评论