Created
May 13, 2015 18:00
-
-
Save darkodemic/55bb3ce03136c7d4a996 to your computer and use it in GitHub Desktop.
Basic pointers in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* main.c | |
* | |
* Created on: May 13, 2015 | |
* Author: Darko Demic | |
*/ | |
#include <stdio.h> | |
//Testing pointers | |
/* a copy of the int n can be changed within the function without affecting the calling code */ | |
void passByValue(int n) { | |
n += 12; | |
printf("The value of x was passed to subprogram and added to value of n and should be 15: %d\n", n); | |
} | |
/* a pointer to m is passed instead. No copy of m itself is created */ | |
void passByAddress(int *m) { | |
*m = 14; | |
} | |
void array_fill(int *ap){ | |
int i; | |
for(i = 0; i < 5; i++){ | |
printf("Insert %d. unit of the array: ", i+1); | |
scanf("%d",&ap[i]); | |
} | |
} | |
int main(void) { | |
int x = 3; | |
/* pass a copy of x's value as the argument */ | |
passByValue(x); | |
// the value was changed inside the function, but x is still 3 from here on | |
printf("passed by value x is not changes and is equal to: %d\n", x); | |
/* pass x's address as the argument */ | |
passByAddress(&x); | |
// x was actually changed by the function and is now equal to 14 here | |
printf("here x was passed by address or rather x's address was passed to subprogram. and now we can change X to be: %d\n",x); | |
puts(""); | |
int array[5]; | |
int *arp = array; | |
//sending arrays location to subfunction | |
array_fill(arp); | |
//Printing array that we filled with numbers | |
puts(""); | |
printf("Your array looks like: \n"); | |
int i; | |
for(i = 1; i <= 5; i++){ | |
printf("%d. Memeber of the array is: %d \n",i, array[i-1]); | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment