Pass back an array from a function (C programing)

Viewed 39

I am trying to make an image of an vector (exercise from school), so I'm using headers. There are two files and one funtion.

First I made an vector

Vector vector;
GLOBAL_ERROR_CODE = initVector(&vector,3);
if(GLOBAL_ERROR_CODE>0) return printGlobalError();                                          
printf("Vector inited\n"); 

Later trying to print it

char * vectorPhotography;
GLOBAL_ERROR_CODE = seeVector( &vector, vectorPhotography );
if(GLOBAL_ERROR_CODE>0) return printGlobalError();                                           

So the seeVector funtion it's this

int seeVector(Vector * vector, char * vectorPhotography){
     char * vectorStrSize = (char *) malloc(sizeof(char));
     int ErrorCode = integerToString(vector->size, vectorStrSize);
     if(ErrorCode>0) return ErrorCode;
     char * arrayPhotography = (char *) malloc(sizeof(char));
     if(ErrorCode>0) return ErrorCode;
     ErrorCode = seeArray(vector->array, arrayPhotography, vector->size);
     if(ErrorCode>0) return ErrorCode;
     if(vectorPhotography) free(vectorPhotography);
     vectorPhotography = (char *) malloc(sizeof("{\nSize:,\nArray:,\n}") + sizeof(arrayPhotography) + sizeof(vectorStrSize));
     if(vectorArray == NULL) return RESERVE_MEMORY_FAIL;
     strcat(vectorPhotography, "{\nSize:");
     strcat(vectorPhotography, vectorStrSize);
     strcat(vectorPhotography, ",\nArray:");
     strcat(vectorPhotography, arrayPhotography);
     strcat(vectorPhotography, ",\n}");
     return 0; 
}

So here's the thing, inside the seeVector funtion after the algorim the value of vectorPhotography is this

(gdb) print vectorPhotography 
$3 = 0x5555557576f0 "{\nSize:\003,\nArray:[][][],\n}"

But when I return to the main function the value is NULL

(gdb) print vectorPhotography
$4 = 0x0

On running I get this

Vector inited
Vector:(null)

So my data it's lost, I don't get how to pass back the vector I have been working on, (I need the return for the error codes)

1 Answers

What you should do is pass a reference to the char array vectorPhotography so that you can access the updated value after the function call. This would involve changing your function signature to int seeVector(Vector * vector, char ** vectorPhotography), changing your function call to seeVector( &vector, &vectorPhotography ) and then changing your usages of vectorPhotography inside of your function to *vectorPhotography so you change the value pointed to by the local parameter

Related