Do not save the string inside the vector

0

Hello in this code gives me an error when I ask the user to enter a string and modify the one that I already entered that is "dog", the problem is in these lines

printf("Ingrese una palabra: ");
    scanf("%s",(vector+1));

If I do not use them, it works well, but I want the user to be able to modify that "dog" that I gave.

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

int main()
{
    int i,j,a;
    char **vector;

    vector = (char**)malloc(2*sizeof(char*));

    *(vector) = "hola";
    *(vector + 1) = "perro";
    printf("Ingrese una palabra: ");
    scanf("%s",(vector+1));

    puts("\nImprimiendo caracter a caracter:");
    for(i=0;i<2;i++) 
    {
        for(j=0; j<strlen(*(vector+i)) ; j++)
        {
            printf("%c",*(*(vector+i)+j));
        }
        puts("");
    }

    puts("\nImprimiendo completo:");
    printf("%s\n",*vector);
    printf("%s",*(vector+1));

    free(vector);

    return 0;
}
    
asked by EmiliOrtega 09.02.2017 в 21:59
source

1 answer

0

You can not modify a char *, I would do so, it's simpler and cleaner. I do not know if it's the best solution since I'm learning.

#include <stdio.h>

#define MAXLINE 100

int main()
{
    int i,j,a;

    char vector[MAXLINE] = "hola "; 
    char temp[MAXLINE] = "perro"; // string temporal para concatenar hola con la modificacion

    printf("Ingrese una palabra: ");
    fgets(temp, MAXLINE, stdin); // obtener el input del usuario

    strcat(vector, temp); // concatenar tu vector con lo que el usuario ingreso
    printf("%s", vector); // imprimirlo por pantalla

    return 0;
}
    
answered by 09.02.2017 в 23:13