Having trouble understanding using a pointer and structs together and passing through a function. Say for example...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
usingnamespace std;
struct the
{
int a;
} numbers;
somefunction (the* pnumbers)
{
24 = pnumbers.a; // not really sure if that's right..
}
int main ()
{
the *pnumbers = NULL;
pnumbers = &numbers;
somefunction (pnumbers);
return 0;
}
all in all I am not really sure if I am passing it right in terms of a struct do pass 'the' as the variable definition? More over am I initializing the data correctly in the function?
# include <iostream>
usingnamespace std;
struct the
{
int a;
}numbers;
void somefunction(the* pnumbers)// Dont forget the function's type
{
// 24 = pnumbers.a; // what are you trying to do here?
pnumbers->a = 24; // because pnumbers is a pointer of a structor,
// to access 'a' you should use the arrow operator.
cout << pnumbers->a << endl;
}
int main ()
{
the *pnumbers = NULL;
pnumbers = &numbers;
somefunction (pnumbers);
return 0;
}
-> is an alternate way for do what techno01 just wrote. You're dereferencing the pointer to get the struct, and as normal you use the . to get the member of that struct. We use -> simply because the other way is ugly. The ( ) are for precedence and * for dereference.
sorry, what I getting confused about is when you initialized
1 2
pnumbers = &numbers;
I thought essentially you are controlling the numbers struct and not entirely different struct called pnumbers? or perhaps I was wording it wrong above what I meant is
# include <iostream>
usingnamespace std;
struct the
{
int a;
}numbers;
void somefunction(the* pnumbers)
{
pnumbers->a = 24;
cout << pnumbers->a << endl;
}
int main ()
{
the *pnumbers = NULL;
pnumbers = &numbers;
somefunction (pnumbers);
cout << numbers.a << endl; // Will this be 24? such are my intentions...
return 0;
}
sorry, what I getting confused about is when you initialized pnumbers = &numbers;
first I did not initialized... you did I just copied your code :)
second dont be confused because we will start from 0
well you declared an instance(numbers) for the structor "the"
then you declared a structor pointer(pnumbers) that points to this object(numbers)
pnumbers = &numbers means that we will take the address of the object numbers ,assign it to pnumbers structor pointer ,so that pnumbers can points all the time at the object numbers
In the function "someFunction" we have an
entirely different struct called pnumbers
but since it take the address of the pnumbers It can access all numbers members ,as I did pnumbers->a = 24;
finaly in main function you can write cout << numbers.a << endl; and it will be 24
also this statement pnumbers ->a =24;
equals to
1 2 3 4
int main ()
{
numbers.a = 24;
}
My mistake I did not pay attention I thought you did put numbers.a in "someFunction" function sorry :(