Reputation: 23
I would like to select an array with a variable in order to copy its values into another array.
I'm struggling with this line : xyz[i] = arr1[i]
;
I want to replace arr1
with the variable name
Something like I use in Bash : xyz[i] = ${name}[i];
Does anyone have any clues or solutions ?
Here's a simplified version of my code
#include <stdio.h>
int main() {
int arr1[8] = {1, 2, 3, 4, 5, 6, 7, 8};
int arr2[8] = {8, 7, 6, 5, 4, 3, 2, 1};
int xyz [8], i, num=8;
int loop;
char name[4];
printf("Array's name ? ");
scanf("%s", &name);
// Array's name ? arr1
for (i = 0; i < num; i++) {
xyz[i] = arr1[i];
}
for(loop = 0; loop < 8; loop++) {
printf("%d ", xyz[loop]);
}
// 1 2 3 4 5 6 7 8
return 0;
}
Upvotes: 0
Views: 883
Reputation: 123508
C doesn't provide this capability (after the source code has been compiled, variable names no longer exist as such). You'll need to use a pointer to do something like this, and you'll need to add logic to assign the right value to that pointer. For a couple of names, a simple if/else
statement is good enough:
int *p = NULL; // p will point to the first element of arr1 or arr2 depending on the value of name
if ( strcmp( name, "arr1" ) == 0 )
p = arr1;
else if ( strcmp( name, "arr2" ) == 0 )
p = arr2;
else
fprintf( stderr, "%s is not a valid name\n", name );
if ( !p )
{
// handle bad entry
}
else
{
for ( i = 0; i < num; i++ )
xyz[i] = p[i];
}
In the general case (where you have more than just a few options), you'll want to build some kind of a map that associates a name with an address:
struct {
char *name;
int *arr;
} name_arr_map[] = {
{"arr1", arr1},
{"arr2", arr2},
...
};
int *p = NULL;
// get name
for ( i = 0; i < N; i++ ) // N entries in our map
{
if ( strcmp( name_arr_map[i].name, name ) == 0 )
{
p = name_arr_map[i].arr;
break;
}
}
if ( !p )
{
// handle bad entry
}
else
{
for ( i = 0; i < num; i++ )
xyz[i] = p[i];
}
For a few entries (a couple of dozen or so) a simple linear search like this is good enough. If you have more than that, you may want to use a more sophisticated structure like a hash table or a tree.
However, for this specific case...
When you find yourself creating multiple variables of the same type with the names thing1
, thing2
, etc., that's a real strong hint you want an array - in this case, a 2D array:
int arrs[2][8] = { { 1, 2, 3, 4, 5, 6, 7, 8 },
{ 8, 7, 6, 5, 4, 3, 2, 1 } };
In this case you don't need a name, just an index:
int idx = 0;
...
printf( "Which array do you want to use, 0 or 1? " );
scanf( "%d", &idx );
if ( idx < 0 || idx > 1 )
{
// handle bad entry
}
else
{
for ( i = 0; i < 8; i++ )
xyz[i] = arrs[idx][i];
}
Upvotes: 2
Reputation: 35522
C does not have the ability to do this. You can either manually do it with if/else
statements or find some sort of hashmap implementation in c like this one in order to map from names to arrays. Note that C++ has a pre-installed hashmap implementation that you don't have to download.
Upvotes: 1