in C. I passed a vector to a function and changed it inside. Why didn’t you change my vector in the main function? because I passed a pointer

Asked

Viewed 48 times

0

#include <stdlib.h>

void matriz_transposta( int l, int c, int *matriz);

int main (void){
    
    int linha = 2, coluna = 2;
    int *mat = (int*) malloc(linha*coluna*sizeof(int));

    mat[0] = 1; 
    mat[1] = 2;
    mat[2] = 3;
    mat[3] = 4;
    
    puts("Matriz original");
    int i, j, k;
        for ( i = 0; i < linha; i++)
            for(j = 0; j < coluna; j++){
                k = i * linha+j;
            printf("%d ", mat[k]);
            }
    matriz_transposta(linha, coluna, mat);
        
        puts("\n");
        puts("Matriz transposta");

        for ( i = 0; i < linha; i++)
            for(j = 0; j < coluna; j++){
                k = i * linha+j;
            printf("%d ", mat[k]);
            }               
}

void matriz_transposta( int l, int c, int *matriz){
    
    int i, j, k;
    int *ptraux = (int *) malloc(l*c*sizeof(int));
    puts("\n"); 
    for (i = 0; i < l; i ++)
        for ( j = 0; j < c; j++){
        ptraux[i*l+j] = matriz[j*l+i];
        printf("%d ", ptraux[i*l+j]);
    }
    matriz = ptraux;
    puts("\n");
    for ( i = 0; i < l; i++)
            for(j = 0; j < c; j++){
                k = i * l+j;
            printf(" %d ", matriz[k]);
            }
    free(ptraux);
    
    
}
  • When you do matriz = ptraux, you are just changing the local value of the pointer within the function. You need to either modify the original matrix itself within the function, or copy the entire contents of the helper to the original (for example, with memcpy(matriz, ptraux, sizeof(int) * l * c)).

1 answer

0


It didn’t change because int* matriz is a copy of the pointer.
The pointer points to the same region, but it is not the same pointer.
Does that explain why: matriz = ptraux only function within the scope of the function

In C, there is no passage by reference, you will always be passing by value.

Browser other questions tagged

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