I am begginr programmer wiyh C. I want to do a work with structure variables, but I don't know how. Could anyone help me?
I have to define a structure variable like bellow:
struct name{
int x;
int y;
}NAME;
I creat some NAME[i] within a loop and set "x" and "y" for all of them (for example 100 NAME[i]). I must also add that the "y" is a unrepeatable number and in all NAME[i] variales (i.e. there are 100 different "y"). After that I get a number (k) equal to one "y" of the NAME variables within another part of my code. I want with this number (k) get the related x (that its "y" is equivalent to this number).
My problem is that I don't know how can I do that?
Thanks in advance,
Cheers
Hi. I was confused by your question at the first place.
You mean you wanted to create 100 instances of your structure called "NAME" is it ? Hope i am not mistaken. Well , the way to create a collection of variable with the type "NAME" should be as below:
But the proper way to create a user define data type in C should be as follow:
. The above code create an array which can store 100 instances or variable of the user define type "NAME". Then your initialize the data member in each member of nameArray[] by using a loop. Note that each member of nameArray[] is indeed a structure that contain 1 integer type call "x" and 1 integer type call "y".
You have mentioned that you want to assign unique number to integer variable y in each variable of NAME type. U didn't mention the expected value of "x". Thus, my suggested method for your question is:
Create N number of variable NAME type and store them in an array as mentioned.
Then, initialize the variable using a for loop.
- for( i = 0 ; i < 100; i ++) {
-
NAME [i].y = i;
-
NAME[i].x = i * i; /* i time i*/
-
}
By using the for loop, u assign a unique number to y and i x i to x. Note the dot operator (.) is used to access each member in every variable of type NAME. After the initilization , you could found your corresponding x by searching the corresponding y using a driver program.
You may need to do some reading on the structure.
I don't understand what do u mean by "not using loop". Then u have to use a sequential way to initialize the value of x and y.