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
Here is the code modified to do what you asked (see notes below):
Still, as others pointed out, doing so is pointless. The reason why types are used is to know two things:
What you are trying to achieve here is a clumsy attempt to do the job of the OS.
To be clear: memory is a contiguous storage and the OS marks it as “allocated” when it is (by functions like
malloc(3)). When it does so, the program has to know the type of a data to know what to read (a pointer is merely an address), and how to interpret it (ints are not stored the same way thatfloats are).If you are genuinely interested in learning such things (how data is stored, how computer works more generally, and at a lowest level than in C#), I’d recommend you to read:
MIPS assembly tutorial (first relevant answer from google, any MIPS asm course would be okay)
x86 Assembly, 6th ed. if you got the money for it.
Also, if you want to test MIPS assembly, mars is a MIPS assembly simulator that works ok (and is free).
I’m glad to see that people are still trying to learn C.