HW 3: C Programming I
Instructions
You must turn in a sheet of paper that is neatly typed or written answering the questions below. (You are strongly encouraged to type your homework.)
You can use the following tex file to get started with preparing your homework.
- This homework is graded out of 90 points. Point values are associated to each question.
Questions
- (5 points) Write a small C program that uses
sizeof()
to report the size in byte of each the types listed below. (You don't need to submit the program, just the sizes.)int
char
int *
float *
char *
short
int **
float
double
- (5 Points) For the sizes above, why is it that all the pointer types, even the double pointer, have the same size in bytes?
(10 points) Rewrite the following C++ code in C:
#include <stdio> using namespace std; int main(int argc, char *argv[]){ int j=10; int k; cout << "Enter a number" << endl; cin >> k; cout << "Num+10: " << k + 10 << endl; }
(10 points) Complete the program below to print "Go Navy" to a new file called
gonavy.txt
, "Beat Army" to abeatarmy.txt
, and "Crash Airforce" to standard error.#include <stdio.h> #include <stdlib.h> int main(int argc, char * argv[]){ FILE * gonavy, *beatarmy; //WRITE THE REST! }
(10 points) For the following program snippet below, there are at least four errors. Enumerate them.
for( int i=0 ; i<5 , i--){ printf(i) }
- (10 points) For the following code snippets, what is the output and explain
that output? (Yes, you should program and run these program to
determine the output!)
unsigned int i = 4294967295; printf("%d\n",i);
int i = 3.1519; printf("%d\n", i);
int i = (int) 1.5 + 2.5 + 3.5 + 4.5 printf("%d\n",i);
(10 points) Consider the program snippet below and the memory diagram representing that programs state at MARK 0. Complete a stack diagram for each of the remaining MARKS 1-4.
int a=0,b=0,*p; p = &b; /* (0) */ *p = 15; /* (1) */ a = b; b = 25; /* (2) */ p = &a; /* (3) */ (*p)++; /* (4) */
Mark 0 Diagram
.----.----. | a | 0 | |----|----| | b | 0 | <-. |----|----| | | p | .-+---' '----'----'
(10 points) What is the values of the array after this code completes?
//statically declaring an array int array[10] = {0,1,2,3,4,5,6,7,8,9}; int * p = array+3; p[0]=2018; //<--- Value of array here?
(10 points) You are trying to copy an array from to another, and you write the following code:
int a[10] = {0,1,2,3,4,5,6,7,8,9}; int b[10]; //copy from a to b a=b;
- Why is this code incorrect?
- Write a corrected code segment by replacing the offensive part
of the code above to copy the values in
b
toa
.(10 points) The program below has at least three things wrong with them. Enumerate them and write the corrected code.
#include <stdlib.h> int main( int argc, char * argv[]){ file * stream; stream = open("file.txt", "r"); fprintf(stream, "Hello World"); return 0; }