Skip to content

Instantly share code, notes, and snippets.

@oz123
Created December 11, 2014 13:55
Show Gist options
  • Save oz123/cd4509f6237c56f363a2 to your computer and use it in GitHub Desktop.
Save oz123/cd4509f6237c56f363a2 to your computer and use it in GitHub Desktop.
Modify arrays inside functions in C. This subject is always tricky and I tend to forget, so here is a not to self.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
/* demonstrate pass by reference of an array of integers*/
void resize( int **p, int size ) {
free( *p );
*p = (int*) malloc( size * sizeof(int) );
int tocpy[]= {8};
/* showing offset from the beginning of an array*/
memcpy(*p + size-1, tocpy, 1);
}
int main() {
int *p;
p = calloc(10, sizeof(int));
for (int i = 0; i < 10; i++)
printf("p[i] %d\n", p[i]);
resize( &p, 20 );
for (int i = 0; i < 20; i++)
printf("p2[i] %d\n", p[i]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment