-3

Here is are the three structures that I'm using and for instance when my program gets 'the' as the first word, it makes *rt->str = the. However when the next word is read, the key is equal to to the *rt->str and I don't understand why. I'm a c programmer beginnner and this has really stoppped me in my tracks.

struct node {
    char *str;
    int occ;
    struct node *sibling;
    struct node *child;
};

struct node* root;

struct node* getNew(char word[100]) {
    struct node *newNode;
    newNode = (struct node *)malloc(sizeof(struct node));
    newNode->str = word;
    newNode->sibling = NULL;
    newNode->child = NULL;
    newNode->occ = 0;
    return newNode;
}

struct node* insert( char key[100], struct node **rt ){

    if(*rt == NULL) {
        *rt = getNew(key);
        printf("This is the key in the root: %s\n", (*rt)->str);
        return *rt;
    }else{
        printf("root word: %s\n", (*rt)->str);
        exit(0);
    }

    struct node *leaf = *rt;
    int n = 0;
    int i;
    char w2[100];
    strcpy(w2, key);

    printf("root word: %s\n", (*rt)->str);

    for(i = 0; i < strlen((leaf)->str); i++) {
        printf("%c %c \n", (leaf)->str[i], key[i]);
        if((key[0] == (leaf)->str[i])) {
            n++;
            key = key + 1;
            printf("key is: %s \n", key);
        }
    }

    if(key[0] == 0) {
        printf("key is empty \n");
    }

    printf("This is the word after for loop: %s \n", key);
    exit(0);
}
Toby
  • 9,696
  • 16
  • 68
  • 132
  • 4
    `if (...) return ..; else exit();` makes the rest of the function unreachable. – mch Mar 01 '17 at 13:01
  • 2
    Learn to use a debugger. You won't get far by asking on SO every single time your code doesn't do what you wanted. – rustyx Mar 01 '17 at 13:02
  • Also in `getNew`, `newNode->str = word;` You probably want to use [`strdup`](http://en.cppreference.com/w/c/experimental/dynamic/strdup) here. – 001 Mar 01 '17 at 13:05

1 Answers1

1

This:

newNode->str = word;

doesn't copy the string (as in, the characters that build up the string), it just copies the location of a string, which is an argument. That location will not remain valid when the function exits, so this gives you undefined behavior when you access it later.

C does not support assigning arrays, and arrays are not pointers.

unwind
  • 391,730
  • 64
  • 469
  • 606