Tuesday, July 14, 2009

C programming array question?

Here's a sample of a program:





char cur[6][20]={"Euro ", "YEN ", "Franc", "ZWD", "DOP", "Exit"}; //five currencies types plus exit option (6)


float rates[5] ={1.3859, 114.9750, 0.8424, 0.00003333, 0.02988}; // five (5)exchange rates








What would the (20) relate to if we are doing currency conversion? Why should the number (20) be used in this example if the conversion is hard-coded why not any other number?

C programming array question?
The cur[6] relate to the five currency options (+Exit) in the array, and [20] is the size of the string in each of the arrays, so the longest currency /option name is "Franc" that is at cur[2]. So there is a 'wasted space' for minimum 14 bytes (1 byte required for string terminating null character \x0) for each array from [0] to [6].


Therefore your declaration may be like char cur[6][6] = {"Euro".......};
Reply:u can use 6 in place of 20 try it


20 is used for length of maximun characters in char variable
Reply:Hi,


Of course, 20 is the maximum length of the string that can be stored in cur[6][20] array. But there is wastage of space. Only "Franc" is using max space, i.e., 5 charachter. Still there is wastage of 15 characters.





Instead of above u could declare a character array of pointers that would save space without writing any fixed size (in this case 20). Still u can save string of any length.





Alternative code of ur code is:


char *cur[6]={"Euro","Yen","Franc","ZWD","DOP...


u can access any of the elements by writing cur[4], cur[0] etc.
Reply:Hi,


I am no expert but i think it's the "Text String Length" in the array,


No comments:

Post a Comment