Skip to content

Instantly share code, notes, and snippets.

@oz123
Created December 11, 2014 23:10
Show Gist options
  • Save oz123/6737a67f6fd66c731297 to your computer and use it in GitHub Desktop.
Save oz123/6737a67f6fd66c731297 to your computer and use it in GitHub Desktop.
accessing array elements ...
#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);
memcpy((*p+size -2), tocpy, 1);
*(*p+6) = 6;
}
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 );
int tocpy[]= {8};
memcpy(&p + 1, tocpy, 1);
memcpy(p + 2, tocpy, 1);
memcpy(&p[3], tocpy, 1);
// directly assign
p[4] = 4;
*(p+5) = 5;
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