I've recently started learning C, so apologies if my question is very basic or unclear.
I'm passing 3 command line values to my program. ( TYPE , LENGTH , VAL). Using these values I want to create an array on the heap of type TYPE and length LENGTH and have all elements initialized to VAL. So for example
float 8 4 : will create a float array with 8 elements each of which will have a value of 4.
char 4 65 : will create a char array with 4 elements, each of which will have a value of 'A'.
Determining the length is straight forward. But I'm struggling to determine how to initialize the pointer to the array and the VAL.
The following is what I've attempted so far (unsuccessfully). I'm initializing a char pointer, however I know this is incorrect as I may need a float or int pointer instead. I'm also using a switch statement based on the first character of the TYPE, to me this seems very hacky.
int main (int argc, char *argv[]){
int LENGTH;
char *ptr;
LENGTH = atoi ( argv[2] );
switch( *argv[1] ){
case 'f':
printf("Type is float\n");
ptr = (float *)malloc(LENGTH * sizeof(float));
break;
case 'c':
printf("Type is char\n");
ptr = (char *)malloc(LENGTH * sizeof(char));
break;
case 'i':
printf("Type is int\n");
ptr = (int *)malloc(LENGTH * sizeof(int));
break;
default:
printf("Unrecognized type");
break;
}
while( i < arrayLength ){
*ptr[i] = *argv[3];
i++;
}
free ( ptr );
return 0;
}
I can also see issues with the initialization element of the problem. The initial value is dependent on the TYPE so made need to be converted.
What I'm wondering is, without knowing the TYPE beforehand, how can I create the pointer or initialize the values? I'm probably looking at this issue from the wrong direction completely, so any advice would be greatly appreciated.
Thanks