I want to declare a two-dimensional array with two different data types in C language. First column and row must be character and they are the same and other elements must be integer. Then, I want to set the values of the elements based on the first column and row. For example:
A B C D
A 1 2 3 4
B 4 3 2 1 a[A][D] = 4
C 9 8 7 6
D 6 7 8 9
I cannot use a[0][3] = 4, because A and D are returned values of another function in my program and I don't know what there indeces are in the array a. If I use another array for my first row and search in it to find the index, it takes too much time and it is not good for the performance of my program.
2 Answers 2
In C, you cannot declare an array, two-dimensional or otherwise, such that some parts of the array are of one type and some are of another type. It is possible to cheat, and use the larger of the two data types for the entire array and then cast a whole bunch, but I do not recommend that idea for your problem, since it's more error-prone and gives up what little illusion of type safety C has.
If I use another array for my first row and search in it to find the index, it takes too much time and it is not good for the performance of my program.
Build a correct solution first, and then optimize if the correct solution isn't fast enough. If you have such a solution, please post it. If not, write it and then, if it isn't fast enough, ask another question on how to optimize it.
Comments
typedef struct
{
// your types here
}second_dimension_t
typedef struct
{
// your types here
second_dimension_t second_d[x];
}first_dimension_t
first_dimension_t first_dimension[x];
first_dimension[x].second_d[x].my_type;
charis actually a numeric type. It can be cast toint