Error creating array of strings

1

I'm having problems trying to initialize a vector of strings so my code looks like this:

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

int main(){
    char *str[3];
    printf("DIGITE QUALQUER STRING: ");
    scanf("%s", str[0]);
    printf("%s\n", str[0]);
    printf("DIGITE OUTRA STRING: ");
    scanf("%s", str[1]);
    printf("%s\n", str[1]);
    printf("DIGITE MAIS OUTRA: ");
    scanf("%s", str[2]);
    printf("%s\n", str[2]);

    /*
    char *str[2];
    str[0] = "abc";
    str[1] = "cba";
    printf("%s\n", str[0]);
    printf("%s", str[1]);
    */
    return 0;
}
When I compile this code the compiler returns no warning and no error, when I execute it and enter with the first value it stops and exits the program so if I decrease my vector to only 2 and enter with the first one value it returns me memory garbage and in the second it returns me to string passed.

If instead of vector I do with just char *str a string it returns me the value passed normally I'm trying to catch the mallet from dynamic allocation I'm almost sure I'm doing something wrong.

    
asked by anonymous 05.09.2017 / 21:47

1 answer

1

It gives you an error because you are not allocating space for strings , just for your pointers. Then either switch to array and allocate it to stack which seems to me more convenient for this case or use malloc() to allocate in heap and return a pointer.

#include <stdio.h>

int main(){
    char str[3][30];
    printf("DIGITE QUALQUER STRING: ");
    scanf("%s", str[0]);
    printf("%s\n", str[0]);
    printf("DIGITE OUTRA STRING: ");
    scanf("%s", str[1]);
    printf("%s\n", str[1]);
    printf("DIGITE MAIS OUTRA: ");
    scanf("%s", str[2]);
    printf("%s\n", str[2]);
}

See running on ideone . And no Coding Ground . Also I put it in GitHub for future reference .

    
05.09.2017 / 22:26