Skip to content

Instantly share code, notes, and snippets.

@hidsh
Created November 16, 2018 19:12
Show Gist options
  • Select an option

  • Save hidsh/5010f7ef5945409a5fc3f6e639a63a75 to your computer and use it in GitHub Desktop.

Select an option

Save hidsh/5010f7ef5945409a5fc3f6e639a63a75 to your computer and use it in GitHub Desktop.
c: test: *p++ = v; is what we will probably want setting values in the loop
// all the same:
// *p++ = x
// *(p)++ = x
// *(p++) = x
//
#include <stdio.h>
void print_arr(int a[])
{
for(int i=0; i<3; i++) {
printf("%d\n", a[i]);
}
}
void set_arr(int *p, int v1, int v2, int v3)
{
*p++ = v1;
*p++ = v2;
*p++ = v3;
}
void set_arr2(int *p, int v1, int v2, int v3)
{
*(p)++ = v1;
*(p)++ = v2;
*(p)++ = v3;
}
void set_arr3(int *p, int v1, int v2, int v3)
{
*(p++) = v1;
*(p++) = v2;
*(p++) = v3;
}
#if 0
void set_arr4(int *p, int v1, int v2, int v3)
{
(*p)++ = v1; // error: expression is not assignable
(*p)++ = v2; // error: expression is not assignable
(*p)++ = v3; // error: expression is not assignable
}
#endif
int main(void)
{
int arr[3];
int *parr = arr;
set_arr(parr, 3, 2, 1);
print_arr(arr);
printf("---------\n");
set_arr2(parr, 6, 5, 4);
print_arr(arr);
printf("---------\n");
set_arr3(parr, 9, 8, 7);
print_arr(arr);
#if 0 // error occured
set_arr4(parr, 111, 444, 777);
print_arr(arr);
#endif
return 0;
}
// result
// ----------------------------------
// ~/test/c ❯❯❯ gcc ptr_plus_plus.c && ./a.out
// 3
// 2
// 1
// ---------
// 6
// 5
// 4
// ---------
// 9
// 8
// 7
// ~/test/c ❯❯❯
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment