1

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.

4
  • 3
    Y dont u use enum to assign numeric values to ur A B C D ??? Commented Feb 20, 2012 at 4:58
  • 2
    Hint: char is actually a numeric type. It can be cast to int Commented Feb 20, 2012 at 5:00
  • How can I use it? Can you explain it with an example? Thanks. Commented Feb 20, 2012 at 5:00
  • What you need is called Hash Table Commented Feb 20, 2012 at 5:24

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0
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;

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.