C arrays and functions, how to return? -


i have newbie question regarding array , functions in c.

let's have array:

int array1[10] = {2,4,6,3,2,3,6,7,9,1}; 

i wrote function:

int *reversearray(int *array, int size) {     int *arr = malloc(size * sizeof(int));     int i, j;      for(i = 10, j = 0; > 0; i--, i++) {         arr[j] = array[i];     }      return arr; } 

i don't know if works, because if do:

array1 = reversearray(array1, 10); 

i got error:

assignment expression array type

how assign adress of array array?

the function correct*, , works fine. problem cannot assign array this:

array1 = reversearray(array1, 10); 

reversearray returns pointer, should assign pointer variable:

int* reversedarray1 = reversearray(array1, 10); 

if want data placed in array1, use memcpy:

memcpy(array1, reversedarray1, sizeof(array1)); free(reversedarray1); 

note since function uses malloc allocate return value, caller needs deallocate memory after done it. need call free(reversedarray1) ensure allocated array not create memory leak.

* use size-1 in place of 10 in for loop header, since passing anyway, , allow i reach zero:

for(i = size-1, j = 0; >= 0; i--, j++) 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -