Skip to content

Instantly share code, notes, and snippets.

@joegasewicz
Last active August 16, 2023 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joegasewicz/ea2ca25065c97b9206d6298c171e82a3 to your computer and use it in GitHub Desktop.
Save joegasewicz/ea2ca25065c97b9206d6298c171e82a3 to your computer and use it in GitHub Desktop.
C Pointers
// * - indirection operator
int *pNumber = NULL, myNum = 1;
char *my_str = "hello";
long num1 = 0L, num2 = 0L, *pNum = NULL;
if (pNumber == NULL)
printf("pNumber is currently NULL\n");
pNumber = &myNum;
for (; myNum<100; myNum++)
;
printf("result: %i\n", *pNumber);
// Out of bounds error occurs if we loop past the index length of my_str
// Decrement too far & will get an under bounds error
for (int i=0; i<5; i++)
printf("result: %c\n", *my_str++);
printf("my_str's address: %p\n", &my_str);
int number = 0;
int *pnumber = NULL;
number = 10;
printf("numbers address: %p\n", &number);
printf("number's value: %d\n\n", number);
pnumber = &number;
printf("pnumber's address %p\n", (void*)&pnumber); // to void for some systems might error
printf("pnumber's size: %d bytes \n", sizeof(pnumber)); // bytes
printf("pnumber's value: %p\n", pnumber); // address
printf("value pointed to: %d\n\n\n", *pnumber);
/* ====================================================================== */
/* Using Pointers */
/* ====================================================================== */
long num1 = 0L;
long num2 = 0L;
long *pnum = NULL;
pnum = &num1;
*pnum = 2L;
printf("num1 = %ld\n", num1); // 2
++num2;
printf("num2 = %ld\n", num2); // 1
num2 += *pnum;
printf("num2 = %ld\n\n\n", num2); // 3
++*pnum;
printf(
"num1 = %ld\n"
"num2 = %ld\n"
"*pnum = %ld\n\n\n"
,num1, num2, *pnum
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment