How to properly traverse a matrix allocated in C?

Asked

Viewed 32 times

1

Whenever I walk through my char matrix (char**) it changes all positions with the value of the last node, example;

char** string = AlocaMatriz(10,10); //retorna uma matriz char** 10x10 allocada
    char aux[1000];
    for (int y = 0; y < 10; y++)
    {
        
        int a = (rand() % 1001);
        sprintf(aux, "%i", a);
        string[y] = aux;        
    }

    for (int y = 0; y < 10; y++)
    {
        printf("y: %d, M: %s \n",y,string[y]);
    }
//retorno
y: 0, M: 123 
y: 1, M: 123 
y: 2, M: 123 
y: 3, M: 123 
y: 4, M: 123 
y: 5, M: 123 
y: 6, M: 123 
y: 7, M: 123 
y: 8, M: 123 
y: 9, M: 123 

but if I add the value without going through the matrix it does not happen:

char** string = AlocaMatriz(10,1000);

string[0] ="123";
string[1] ="321";
string[9] = "332";

for (int y = 0; y < 10; y++)
{
    printf("y: %d, M: %s \n",y,string[y]);
}
 //retorno
y: 0, M: 123 
y: 1, M: 321 
y: 2, M:  
y: 3, M:  
y: 4, M:  
y: 5, M:  
y: 6, M:  
y: 7, M:  
y: 8, M:  
y: 9, M: 332

I need to go through this matrix by adding different value to each of the positions. How could I do this?

  • your question is very confusing, want to "go through" the matrix so what exactly? if it is to show what you have do not really need to change. Now this line string[y] = "123"; will reap the same value for all matrix elements, you know said right?

  • Oops, I just saw the error in the example. I’ll fix it with random numbers.

  • 1

    Here: string[y] = aux; you are assigning tostring[y] the address of aux therefore you will be assigning the same address for all elements of string, so in the print loop will be printing the same value that is the last assigned in sprintf(aux, "%i", a);.

  • Post an entire program, compileable.

  • What you wrote is not so correct. You would have to post Alocamatriz() so that you can understand what you are trying to do. In C there is no such concept of matrix, as it has in FORTRAN for example. Only vectors, eventually vector vectors and so on. When declaring matrix as char** and using a row-and-column-based function to implement this remember the main prototype(): int main( int argc, char** argv) and think why there is argcand what is a char**. You must build as delcarou.

1 answer

1


Taking into account that you have allocated space for string[y], replace

string[y] = aux;

for

strcpy(string[y], aux);

Remember to include <string.h>

strcpy copies a string to another string. Assigning auxfor string[y] you are assigning only the address for the variable. When aux changes, the value changes to all variables as they are all a pointer to the same string.

  • you can also use direct sprintf in string[y]: sprintf(string[y], "%i", a);

  • 1

    Thank you, that’s right

Browser other questions tagged

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