Copy Strings in C

Asked

Viewed 5,124 times

3

I have the following two-dimensional matrix of strings. char matriz[linhas][tamanhoDaString] Through the strcpy I copied a string there.

char *aux = "abc";
strcpy(matriz, aux);

My goal was to put in linha 3 the string aux.

How can I solve my problem?

  • Try: strcpy(matrix[2], aux); (whereas the index part of 0 and therefore the third row is matrix[2]).

  • See test at: http://ideone.com/Gk6tdH

  • @Urbester: I suggest you turn on your compiler warnings.

  • I have the warnings on, I am compiling directly on the linux console. I have already solved the problem.

2 answers

5

matriz is not a string: it is an array of strings. You can’t use matriz directly in office str*; you have to use its elements.

The third element of matriz is matriz[2], that element is (or rather, it can be) a string.

const char *aux = "abc"; // eu gosto de por o const para o compilador me
                         // avisar se eu tentar alterar o conteúdo de aux
if (strlen(aux) >= sizeof *matriz) {
    // o tamanho de cada elemento de matriz
    // nao é suficiente para o comprimento de aux
} else {
    strcpy(matriz[2], aux);
}
  • 2

    Don’t forget to take the null terminator into account! Use stdlen(aux)+1.

  • 2

    @Guilhermebernal: thank you for the reminder; the >= already takes care of the terminator.

2


Just put the index, because then you specify the position of your 2D array you want to copy the value:

strcpy(matriz[2], aux);

Browser other questions tagged

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