#include <iostream>
usingnamespace std;
int main()
{
struct pop {
int *a;
int b;
}
system("PAUSE");
}
How would you use or assign a value to a? I don't get how you access those since I have never used pointers like that within a structure.
Also say you have something like
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std;
int main()
{
struct pop {
int a;
int b;
}*can
system("PAUSE");
}
The pointer int a is gone but there's a pointer to identifier can. How do you set values to a and b with can now seems impossible? I'm just not also getting this can someone explain?
a is a normal member, you access it as any other type of member. It being a pointer only changes how you use it.
Second
1 2 3
can->a = 7;
//or
(*can).a;
The second variant should be clear. You first apply * to get the object 'can' points to and then use . as you do with all objects. -> is just a cleaner way to write the same thing.
The both examples contain error because you did not place ; after structure or pointer to sttructure definitions.
A pojnter is like other members of structure. You can assign it value the same way as and for other members.
For example,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
struct pop
{
int *a;
int b;
};
pop str1;
str1.a = 0;
str1.b = 0;
pop str2;
str2.a = newint( 10 );
str2.b = 10;
As for the second example, you can either allocate structure in heap and assign its address to your pointer, or assign address of local object of type structure to your pointer.
For example,
1 2 3 4 5 6 7 8 9 10
struct pop
{
int a;
int b;
}*can;
can = new pop;
can->a = 10;
can->b = 10;
or
1 2 3 4 5 6 7 8 9
struct pop
{
int a;
int b;
}*can;
pop str = { 10, 10 };
can = &str;
Some of this though is still extremely annoying and hazy. I've never quite 100% got this pointer concept and I'm really trying to wrap my mind around it it just doesn't make sense.
#include <iostream>
#include <new>
#include <string>
usingnamespace std;
int main()
{
struct pop{
int *a;
int b;
};
pop time;
time.a = newint(1);
int[] as = {10, 20};
time.a = &as;
//output
cout << time->a << " Done" << endl;
//pause
system("PAUSE");
return 0;
}
So in my code there you are creating dynamically an array of two 0 and 1 with time.a. Now let's say we want to use the values from the array as within that dynamic memory. Why can't I get it to point at that and output it? Wouldn't you then point to the memory address of as?
What am I missing can someone try to explain this in a way that I can understand it and understand the science of how to get that to then point to as?