I have declared a structure st below with a struct variable arr[], an array of structs. Im trying to assign the value 1 to the 'num' variable, and values 1 to 10 to 'val' variable of the first 10 locations of array arr[]. And value 2 to 'num' and values 11 to 20 to 'val' of the next 10 locations. But when i traced the code, it won't assign values to the respective num and val of the same array location. If i wanted to assign num=1 and val=4 to the 4th structure it would assign num=1 to val of 3rd structure and val=4 to num of 4th structure. I have no idea why this is happening.

#include<iostream.h>
#include<conio.h>


class abc
{

 public:

 struct st
 {
  int num;
  int val;
 };

 st arr[21];

 void funct();

};

void abc::funct()
{
 int i,j,k=1;

 for(i=1;i<=2;i++)
 {
  for(j=1;j<=10;j++)
  {
   arr[k].num=i;
   arr[k].val=j;
   k++;
  }
 }

}


int main()
{
 abc z;

 z.funct();

 return 0;
}

Don't use conio. Also use a vector as the array isn't contingously aligned. A nice constructor to allow dynamic sizing. Also if you wanted it to continously add 10, you have to store the value it was currently at, add 10 to it and add 10 to the initial. I rewrote the loop for you. You can probably change it to (int J = 1 + Old; J <= Old + 10; ++J); same thing -- one less variable.

#include <iostream>
#include <vector>


class abc
{
    public:
        struct st
        {
            int num;
            int val;
        };

        std::vector<st> arr;

        abc() {}
        abc(int Amount) : arr(Amount) {}
        void funct();

};

void abc::funct()
{
    int Old = 0, L = 10, K = 0;
    for(int I = 1; I <= 2; ++I)
    {
        for(int J = 1 + Old; J <= L; ++J)
        {
            arr[K].num = I;
            arr[K].val = J;
            ++K;
        }
        Old += 10;
        L += 10;
    }
}


int main()
{
    abc z(21);
    z.funct();
    for (int I = 0; I < 21; ++I)
    {
        std::cout<<"Num: "<<z.arr[I].num<<std::endl;
        std::cout<<"Val: "<<z.arr[I].val<<std::endl;
    }

    return 0;
}

The first element of all arrays is numbered 0, not 1. array arr has valid indices 0, 1, 2, 3, ... 20. The initial value of k should be 0, not 1.

Also use a vector as the array isn't contingously aligned.

It isn't? Please explain...

And why do you guys always suggest vectors when they are obviously beyond the scope of their knowledge? What do you think would happen when they turn in their homework with vectors which hasn't been taught???

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.