How to print a string from a string vector in C?

0

I have a string vector ( palavras[x][y] ) , I can read every word that will be an element of the vector, but I can not print any of these stored words.

printf("%s",palavras[a][b]), does not work.

Here are my attempts:

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

int main(int argc, char *argv[])
{
char nomes[1][15];
int i;
scanf("%s",&nomes[0][15]);
scanf("%s",&nomes[1][15]);
printf("%s",&nomes[0][15]);
// for(i=0;i<=15;i++){
// printf("%c",nomes[0][i]);
// }
system("PAUSE");    
return 0;
}

The% commented commented also did not work. How can I proceed?

    
asked by anonymous 04.10.2017 / 00:02

1 answer

1

If you were trying to create a vector of 2 strings , as indicated in the comment, then the size did not work out because it was declared as char nomes[1][15]; and therefore it was 1 size.

Both scanf s and printf s are not sure. Let's look at the first scanf :

scanf("%s",&nomes[0][15]);

You are trying to read a string ( %s ) but then it passes the 16th caratere address of the first string .

Instead you should do just this:

scanf("%s",nomes[0]);

No for was also trying to print letter by letter but this is a lot more complicated than printing string all with %s , as well as stopping the %code% terminator, or getting incorrect.

Hitting these details your code would look like this:

int main(int argc, char *argv[])
{
    char nomes[2][15]; //agora com tamanho 2

    scanf("%s",nomes[0]);
    scanf("%s",nomes[1]);
    printf("%s",nomes[0]);

    int i;
    for(i=0; i<2; i++) {
        printf("%s ",nomes[i]); //agora com %s
    }

    return 0;
}

See the Ideone example

    
04.10.2017 / 01:02