class::struct::char*

Hello community. I'm new here. I've signed up because I hope to find some solutions when I have some problems with my codes.

However, my first error is an access violation. My code is built up as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class theClass {
    struct theStruct {
        char *name;
        struct theSubStruct{
            char *name;
        } *substruct;
    } *structVar;
    
    /* Other methods are not important */
    void write( void );
};


/* The Method */
void theClass::write( void ) {
    structVar[ 0 ].substruct[ 0 ].name = "Foo"; // Exactly here the error occurs
    return;
}



Does anybody know the answer to this? I realy am clueless and for usual I try to solve all my problems by my own... ^^'

All I want is to write into this array of characters... It works fine with another struct a level lower.

DarkDragon1993
It is impossible to say what the problem is because you haven't posted all the code.

For example, structVar is a pointer. I don't see any code where that pointer is initialized
to make structVar[ 0 ] semantically ok. Likewise with substruct.

But just to be clear ... line 16 above does not copy the string "Foo" to name. Rather,
it assigns the name pointer to point to a (read-only) portion of memory (probably in
your program's code segment) that contains the string "Foo".

Ah, yes, okay. Actually, there really is no code to initialize the pointer... I'm a bit new to OOP with C++... ^^'
So I think since <string.h> is already included I could write strcpy( structVar[ 0 ].substruct[ 0 ].name, "Foo" ); instead of the original code... Correct me, when I'm wrong.

Now I understand why it works with the other struct... It is no pointer. :)

Anyway, thanks for your reply. A little googling solved the remaining issues.

DarkDragon1993
As long as you initialize all the pointers.

But since you have to initialize structVar[0].substruct[0].name before the strcpy anyway, rather
than using strcpy you could use strdup, which does the malloc for you, ensuring the resulting
buffer is large enough to hold the source string.
Topic archived. No new replies allowed.