Hi,

I have stupid question. I have array like this.

float *numbers[] = {5; 6; 9; 10};

I need to use for example float = 5 for arrays numbers[0], numbers[1], numbers[2], numbers[3]. Then array float = 6 for numbers[4] and numbers[5] etc. Hope you undestand.

Is there some syntax like for numbers[0 to 3] use first number, for numbers [10..n] use float = 10, etc.

Please help.

Then I need to use variable int i for

printf("%d. number is: %f", i, numbers[i]);

Hope you undestand.

Not even a little bit. Please rephrase your question.

I have this array:

float *numbers[] = {5; 6; 9; 10};

I need to use it with this code:

printf("%d. number is: %f", i, numbers[i]);

I don't know if it's possible in C. I need to print number 5 (from my array) if variable i >=0 && <=3. Then print number 6 if i = 4. Number 9 if i >=4 && <=8 and number 10 if i>=9 to inf. How can I make that?

Do you understand now? I am not good in explaining in English. Thanks anyway.

I see. You want a range of numbers to reference an index in the array. I guess you're looking for some magic solution, but it doesn't exist. You'll need to perform the mapping manually either with a lookup table or a chain of selection statements:

#include <stdio.h>

int get_index(int value)
{
    if (value >= 0 && value <= 3)
        return 0;
    else if (value == 4)
        return 1;
    else if (value >= 5 && value <= 8)
        return 2;
    else if (value == 9)
        return 3;
    else if (value == 10)
        return 4;
    else
        return 0;
}

int main(void)
{
    int numbers[] = {1, 2, 3, 4, 5};
    int i;
    
    for (i = 0; i < 10; i++)
        printf("numbers[%d] == %d\n", i, numbers[get_index(i)]);
        
    return 0;
}

OK. I thought that there is some better solution than with if. Thanks anyway.

Well, there's the switch statement:

#include <stdio.h>

int get_index(int value)
{
    switch(value)
    {
      case 0:
      case 1:
      case 2:
      case 3:
        return 0;

      case 4:
        return 1;

      case 5:
      case 6:
      case 7:
      case 8:
        return 2;

      case 9:
        return 3;

      case 10:
        return 4;

      default:
        return 0;
    }
}

int main(void)
{
    int numbers[] = {1, 2, 3, 4, 5};
    int i;
    
    for (i = 0; i < 10; i++)
        printf("numbers[%d] == %d\n", i, numbers[get_index(i)]);
        
    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.