Using a pointer to a struct in a function

Hi there,

as written above i'm trying to use a pointer to a struct in a function. But somehow i can't dereference it. Either *pd.name, nor *(pd.name) worked for me (here name is a char array, but it didn't work with any other type as well).
The code is from an exercise, when i try to compile an error occures.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cstdlib>
using namespace std;

struct date
{
	int day, month, year;
	char sdate[11];
	long daycount;
};

void getTMJ (date* pd);

int main()
{
...
}

void getTMJ (datum* pd)
{
	cout << *pd.sdatum; // <- error
}


Can anyone tell me, how to correctly do this?
Thanks in advance any effort.

EDIT (after reply): 'datum' must be 'date', wanted to translate it to english but forgot some. this is for future readers.
Last edited on
Hi,

Pointers to structs has so much usage that an operator was invented for it. Check out the -> operator - in the reference at top left of this page.

std::cout << pd->sdatum;

Your problem comes from the tighter binding of the . operator over the * operator.

(*pd).sdatum;

So this forces the de-reference of the pointer first, followed by the access to the struct member. Prefer to use the -> operator, it is just easier.

Hope all goes well.

Edit:

Ordinary pointers don't seem to be used that much in modern C++, consider using a reference instead, or for a more advanced topic, smart pointers. Read up about references.

The other thing is the use of STL containers. I imagine that you might want a collection of date data, so if you put them all into a std::vector say, then you can refer to them by their position - just like an array & not need to use pointers or references at all.
Last edited on
Thanks a lot!
For now i am bound to regular pointers, because the exercises we get in exams are all making use of it. Anyway, it can't be wrong to learn something about it.
No worries, hope you have fun & learn heaps :+)
Topic archived. No new replies allowed.