Error while creating string array

Asked

Viewed 76 times

1

I’m having trouble trying to initialize a vector of strings my code is 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 me no warning and no error, when I run it and enter the first value it stops and exits the program so if I decrease my vector to only 2 and enter the first value it returns me memory junk and the second returns me to string past tense.

If instead of vector I do with just char *str one string it returns me the past value normally I’m trying to catch the dynamic allocation mace I’m almost sure I’m doing something wrong.

  • You want to allocate the string in the stack or in the heap?

2 answers

1


Gives error because it is not allocating space for strings, only for your pointers. Then either changes to array and allocates in stack what seems most convenient for this case or use the malloc() to allocate into 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]);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • well what I wanted to do was create an array of strings without having to use a limit for the size of the string but I can see that it’s not a good thing to do this. in relation to stack, stack and allocation I’m still not very familiar with it but vlw by help

0

The post is old, and already has a correct answer, however, I believe it can help new users.

Do not use scanf to get keyboard input. Scanf has no limit set, if the user input is greater than the allocated space, it will be possible to perform the overlow buffer technique.

I suggest:

#include <stdio.h>

#define BUFFER_TAMANHO_MAXIMO 30

int main(void) {

        char str[3][BUFFER_TAMANHO_MAXIMO];

        // -1 para incluir o NULL_BYTE \0 no final da string.
        fgets(str[0], BUFFER_TAMANHO_MAXIMO - 1, stdin);        
        puts(str[0]);
        return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.