int n; int *p, *q;What will happen when each of the following statements are executed (in order)?
p = &n; *p = 5; *q = 17; q = p; *q = 8;
p = &n; // p will point to n *p = 5; // 5 will be stored into n *q = 17; // the program will attempt to store 17 into the address given by q, // which could cause an error because q has not been initialized. // dcc will give us a warning about this q = p; // q will point to the same address that p does, ie n *q = 8; // 8 will be stored into n
int main(void) { int scanfResult; int a, b, c; scanfResult = scanf("%d %d %d", &a, &b, &c); printf("%d %d %d %d", scanfResult, a, b, c); }
void swap (int x, int y); int main(void) { int x = 10; int y = 99; printf("%d %d\n",x,y); swap(x,y); printf("%d %d\n",x,y); return EXIT_SUCCESS; } void swap (int x, int y) { int tmp; tmp = x; x = y; y = tmp; }
The program passes copies of the values in x and y into the function, so any changes made in the function are only made on the local copies. x and y in the main function remain unchanged. So the output is. 10 99 10 99
void swap (int *x, int *y);
void swap ( int *x, int *y ); int main(void){ int x = 10; int y = 99; printf("%d %d\n",x,y); swap(&x,&y); printf("%d %d\n",x,y); return EXIT_SUCCESS; } void swap (int *x, int *y){ int tmp; tmp = *x; *x = *y; *y = tmp; }
The program passes addresses of the variables in x and y into the function, so any changes made in the function are made by going to the addresses of the original x and y variables and modifying the values in them. This means that the values x and y in the main function are changed. 10 99 99 10
float ff[] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6}; float *fp = ff;
What are the similarities between ff
and fp
? What are
the differences?
ff
.
They can both be used to access the array.
int x = -9; int *p1 = &x; int *p2; p2 = p1; printf("%d\n", *p2); *p2 = 10; printf("%d\n",x);
-9 10
void sumProd(int nums[], int len, int *sum, int *product);
#include <stdio.h> void sumProd(int nums[], int len, int *sum, int *product); int main(int argc, char *argv[]){ int nums[] = {3,4,1,5,6,1}; int prod; int sum; //Pass in the address of the sum and product variables sumProd(nums, 6, &sum, &prod); printf("The sum is %d and prod is %d\n",sum,prod); return 0; } // Calculates the sum and product of the array nums. // Actually modifies the variables that *sum and *product are pointing to void sumProd(int nums[], int len, int *sum, int *product) { int i; *sum = 0; *product = 1; for (i = 0; i < len; i = i + 1) { *sum = *sum + nums[i]; *product = *product * nums[i]; } }