Почему меняется значение sentense.words[0]?

#include <stdio.h>
#include <stdlib.h>
struct word{
    char* syms;
};

struct sentense{
    struct word** words;
};

int main(){

    struct word word;
    struct sentense sentense;
    word.syms = malloc(100*sizeof(char));
    sentense.words = (char*)malloc(100*sizeof(char*));

    word.syms[0] = '1';
    word.syms[1] = '2';
    sentense.words[0] = word.syms;

    word.syms[0] = '4';
    word.syms[1] = '5';
    sentense.words[1] = word.syms;


    printf("%s",sentense.words[0]);
    printf("%s",sentense.words[1]);


    return 0;
}

Почему выводится 4545, а не 1245?


Ответы (1 шт):

Автор решения: Arty

Как сказал @avp, можно использовать strdup.

Не забывайте, что важно освобождать всю выделенную через malloc() память в конце программы используя free(), я для простоты и демонстрации не делал этого, т.к. не делали это и вы, но освобождать всегда очень важная практика!

Полный доработанный вариант вашего кода:

Попробовать онлайн!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct word{
    char * syms;
};

struct sentense{
    struct word ** words;
};

int main(){
    struct word word;
    struct sentense sentense;

    word.syms = (char *)malloc(100 * sizeof(char));
    sentense.words = (struct word **)malloc(100 * sizeof(struct word*));

    word.syms[0] = '1';
    word.syms[1] = '2';
    word.syms[2] = 0;
    sentense.words[0] = (struct word *)malloc(sizeof(word));
    sentense.words[0]->syms = strdup(word.syms);

    word.syms[0] = '4';
    word.syms[1] = '5';
    word.syms[2] = 0;
    sentense.words[1] = (struct word *)malloc(sizeof(word));
    sentense.words[1]->syms = strdup(word.syms);

    printf("%s", sentense.words[0]->syms);
    printf("%s", sentense.words[1]->syms);

    return 0;
}

Выход:

1245
→ Ссылка