-1

When I try to save variable to two dimensional array, it saves it in two dimensions [0] [1] instead of one.

For example:

  • dodajDoKolejki(1,1) // Adding numer 1 to dimension 1

  • priting array gives me result shown below, but it shouldn't change kolejka[0]

    kolejka[0] = 0 0 1 0 0 0 0 0 0 
    kolejka[1] = 1 0 0 0 0 0 0 0 0
    

int (*kolejka)[2]; // Global variable
...
int queue[2][ilSamochodow+1]; 
kolejka = &queue;
...

    void dodajDoKolejki(int numerWatku,int miasto)
    //Adding numbers from 1-... to random dimensions (given as miasto)
    {
        //Checking if number already exists( int istnieje ) in array
        int istnieje = 0;
        int i;
        for(i=0;i<ilSamochodow+1;i++)
        {
            if(kolejka[miasto][i] == numerWatku)
                istnieje = 1;
        }

        if(istnieje == 0)
        {
            //Looking for 0 in array, if found we can save on its index( == 0)
            i = 0; // Indeks miejsca, w ktorym zapiszemy numerWatku
            while(kolejka[miasto][i] != 0)
                i++;

            kolejka[miasto][i] = numerWatku;
            printf("\nDodano %d do kolejki miasta %d",numerWatku,miasto);
            wypiszKolejke2(miasto);
        }
        else
            printf("\nBlad. Nie mozna dodac, poniewaz watek jest w kolejce!");
    }
Conrad
  • 536
  • 5
  • 13

2 Answers2

3

The dimensions and assignment of your kolejka variable are incorrect. Should be:

int (*kolejka)[ilSamochodow+1]; // Global variable
int queue[2][ilSamochodow+1]; 
kolejka = queue;

based on how you are trying to use it. queue is an array of pointers to an array of ilSamochodow+1 ints. So to declare a pointer that is compatible with queue, you need to declare a pointer to an array of ilSamochodow+1 ints.

mshildt
  • 8,782
  • 3
  • 34
  • 41
0

This ...

int (*kolejka)[2]; // Global variable

... declares a pointer to an array of 2 ints. This ...

int queue[2][ilSamochodow+1]; 

... declares an array of 2 arrays of ilSamochodow+1 ints. Therefore, this ...

kolejka = &queue;

... assigns a pointer of incompatible type to variable kolejka. (Your compiler ought to be warning you about that.) Dereferencing the pointer therefore produces undefined behavior.

You would be ok if you instead declared queue like this:

int queue[ilSamochodow+1][2]; 

or if you declared kolejka like this:

int (*kolejka)[ilSamochodow+1];

Since kolejka is a global, the latter supposes that ilSamochodow resolves to a compile-time constant, which appears unlikely to be the case for you.

Additionally, although &queue and queue resolve to the same address in most contexts, they have different type (as discussed elsewhere on SO). Once the order-of-dimensions issue is cleared up, the type-correct assignment would be:

kolejka = queue;
Community
  • 1
  • 1
John Bollinger
  • 160,171
  • 8
  • 81
  • 157