| re: C++: Pointer to a string in a class
* Tomas:[color=blue]
>
> I have a problem with strings.
> I have defined this class:
>
> class wort_cl
> {
> int haeufigkeit;
> int length;
> string wort;
>
> public:
> wort_cl();
> wort_cl(string wort_neu, int haeufigkeit_neu);
> void init(string wort_neu, int haeufigkeit_neu);[/color]
Design: avoid reinitialization of an object.
[color=blue]
> int getHaeufig();
> int getLength();
> string getWort();
> void flush();
> };
>
> Now I want to implement a list with these elements:
>
> struct list_element_t
> {
> wort_cl *daswort;
> struct list_element_t *next;
> };[/color]
Style: using 'struct' as a type prefix is a C'ism, not necessary
and generally not a good idea in C++.
[color=blue]
> The list elements are dynamically created using malloc();[/color]
Principle: 'malloc' is a C'ism and not just stylewise: use type-safe
C++ operator 'new'.
[color=blue]
> void insertList(list_handle_t *h, void *d,int length) {
> struct list_element_t *l;[/color]
Style: using 'struct' as a type prefix is a C'ism, not necessary
and generally not a good idea in C++.
[color=blue]
> l = (struct list_element_t *)malloc(sizeof(struct list_element_t));[/color]
Style: using 'struct' as a type prefix is a C'ism, not necessary
and generally not a good idea in C++.
Style: don't use the lowercase letter 'l' as a name.
Principle: 'malloc' is a C'ism and not just stylewise: use type-safe
C++ operator 'new'.
[color=blue]
> ...
>
> *d is a pointer to a wort_cl object[/color]
Why have you declared it as 'void*' then? Don't do that. Smack,
smack, smack!
[color=blue]
> Now I can't figure out how to
> initialise the element l->daswort so that it contains the same value
> as d.[/color]
That's because you have declared 'd' as 'void*'.
[color=blue]
> When I try something like
>
> *(l->daswort)=*((wort_cl*)d);[/color]
Don't use C style casts.
Don't use casts.
[color=blue]
> I get an access violantion.[/color]
The 'list_element_t' that 'l' points to is not initialized so 'daswort'
inside it is not initialized so dereferencing 'daswort' gives an access
violation because you were lucky -- it's formally undefined ubehavior.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail? |