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?– Ricardo Pontual
Oops, I just saw the error in the example. I’ll fix it with random numbers.
– Guilherme silva
Here:
string[y] = aux;
you are assigning tostring[y]
the address ofaux
therefore you will be assigning the same address for all elements ofstring
, so in the print loop will be printing the same value that is the last assigned insprintf(aux, "%i", a);
.– anonimo
Post an entire program, compileable.
– arfneto
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 isargc
and what is achar**
. You must build as delcarou.– arfneto