Jump to content

Porque é que o meu array de strings está a guardar lixo?


joanacs

Recommended Posts

typedef struct data_cliente client;
struct data_client {
    char *subscription_list;
};

void save_subscription(char topic_chosen[50]){

    client c;
    int j;

    c.subscription_list = malloc(strlen(c.subscription_list) + 1);
    if(c.subscription_list == NULL){
        printf("\n[ERROR] Memory allocation.");
        exit(0);
    }
    else{
        strcpy(&c.subscription_list[strlen(c.subscription_list)], topic_chosen);
    }   

    for(j=0; j<strlen(c.subscription_list); j++)
        printf(" %s", &c.subscription_list[j]);
}

Eu estou a tentar guardar uma string num array dinâmico de strings mas estou a ter alguns problemas. Eu só quero alocar algum espaço para uma string de cada vez e salvá-la, para que da próxima vez possa adicionar outra string ao array, mas manter as outras já adicionadas. O meu código neste momento está a salvar lixo juntamente com a string que eu pretendo e se eu tentar adicionar uma segunda string ao array, a primeira desaparece. Alguém me pode ajudar?

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.