CSC 322 Exam #2

Ace your homework & exams now with Quizwiz!

What is the difference between a declaration and a definition of a variable or function?

A declaration occurs once, but a definition may occur many times.

Explain the difference between #include <blue.h> and #include "blue.h"?

"" searches directory of source first, then standard places.<> search standard places only.

Give the syntax for a function {declaration|definition}.

<Function type> <name> (<argument declarations>){ <local variable definitions> <statements> [return [(<return value>)]}

Rewrite the following for loop as a while loop.ifor (Index = 1;Index < MAX;Index++) { printf("%d\n",Index); Total += Index; }

int Index = 1; while(Index<MAX) { printf("%d\n",Index); Total+= Index; Index++; }

Given the multidimensional array float values[4][3];, what is the equivalent pointer expression for values[2][2]?

((values + 2)+2)

Define preprocessor macros to select: the least significant bit from an unsigned char the nth (assuming least significant is 0) bit from an unsigned char.

#define LSB(X)

Define a preprocessor macro SWAP(t,x,y) that will swap two arguments x and y of a given type t.

#define SWAP(t,x,y) (t = x, x = y, y = t)

Write a program that prints out the date and time is was compiled.

#include <stdio.h> #include <time.h> int main() { time_t t; time(&t); printf("\n This program has been written at : %s", time(&t)); return 0; }

Write code that defines a macro CHOOSE. If the symbol LARGE is defined CHOOSE should return the larger of its two arguments, otherwise it should return the smaller.

#include <stdio.h> #ifdef LARGE #define CHOOSE(A,B) (((A) > (B)) ? (A) : (B)) #else #define CHOOSE(A,B) (((A) < (B)) ? (A) : (B)) #endif //----------------------------------------------------------------------------- int main(void) { int i1,i2; printf("Enter two integers :"); scanf("%d %d",&i1,&i2); #ifdef LARGE printf("The large one is %d\n",CHOOSE(i1,i2)); #else printf("The small one is %d\n",CHOOSE(i1,i2)); #endif }

Write char lower(char c1) which returns the lower case of c1, using a conditional expression to test for that case of c1.

#include <stdio.h> char lower(char c1){ return (c1>='A' && c1<='Z')?(c1+32):c1; } int main() { printf("%c\n", lower('A')); printf("%c\n", lower('a')); return 0; }

Write a program that declares an array of 10 pointers to char, then reads 10 lines from the user, dynamically allocates enough memory for each line after it is read, and makes successive members of the array point to the dynamically allocated memory. When done, the program must then release all the dynamically allocated memory.

#include <stdio.h>#include <stdlib.h>#include <string.h> int main(){char *Array[10]; //declares an array of 10 pointers to charint i = 0;char line[100]; //char array to read and store a lineint length; for(int i = 0; i < 10; i++){fgets(line, 100, stdin); //read a line of max 100 characterslength = strlen(line); //get the length of line stringline[length] = '\0'; //place a Null character at the end of lineArray[i] = malloc(sizeof(char) * length); //dynamically allocates enough money for each linestrcpy(Array[i], line); //copy the line content to he dynamic memory}for(int i = 0; i < 10; i++){ //print the pointer index and the to which each pointer pointsprintf("Pointer %d: Line: %strcpy", i+1, Array[i]);} for(int i = 0; i < 10; i++) //free the dynamic memory used for linesfree(Array[i]);return 0;}

Write a program that takes integers as command line arguments, sums them, and returns the sum back to the operating system.

#include <stdio.h>#include <stdlib.h>//main or driver method that takes command line argumentsint main(int argc, char *argv[]){int sum = 0; //to store the sum//run a loop to iterate over all the command line argumentsfor(int i=1;i<argc;i++){int num = atoi(argv[i]); // convert the argument to numbersum = sum + num; //add it to sum}//return sum to OSreturn sum;}

Write void squeeze(char s1[],char s2[]), that deletes each character in s1 that matches any character in s2.

#include <stdio.h>void squeeze(char s1[], char s2[]); int main(){ char s1[] = {"The course of true love never did run smooth"}; char s2[] = {'a', 'e', 'i', 'o', 'u'}; squeeze(s1[], s2[]); } void squeeze(char s1[], char s2[]){ int a, i, j, k; for(i = j = 0; s1[i] != '\0'; i++){ if(s1[i] != s2[k++]){ s1[j++] = s1[i]; } s1[j] = '\0'; } printf("%s", s1);}

Find out if the version of C you are using does sign extension when converting char to int.

...

typedef a structure suitable for holding information about a radio station, including it's 4 character code name (e.g., ZETA), it's catch phrase (e.g., "ZETA Rocks"), it's frequency (e.g., 94.9), and the number of employees (e.g., 27).

...

Write a conditional compilation statement that, depending on whether or not the symbol LOCAL is defined, includes the file string.h from the current directory (LOCAL is defined) or from the standard splace (LOCAL not defined).

// if LOCAL is defined #ifdef LOCAL #include "string.h" // if local is not defined #else #include <string.h> #endif

What are the key features of {automatic|register|external|static} variables?

1) Local variables and formal parameters have, by default, the storage class auto. Automatic variables come into existance on invocation and disappear when the function is exited. 2)A variable declared to be register informs the compiler that it will be used heavily. Where possible such variables are maintained in machine registers. This is achieved by preceeding the declaration with the word register. Register can only be applied to automatic variables and function arguments (which are automatic). 3)Objects may be declared static to make them permanent or private. This achieved by prefixing the definition with the word static. Internal static variables in functions remain in existance even after the function has exited. Very useful indeed. 4)All objects defined at the outer level in a file, e.g. functions, are external objects. Externals are defined once only, but may be declared often. Each function that uses an external object must either declare it with an explicit extern declaration, or the object must be declared earlier in the same file to provide an implicit declaration.

What does the -D flag do when using gcc? What is an alternative to using the -D flag?

1) The gcc -D flag is used to define a macro for the Preprocessor. This macro is used by the Preprocessor. 2) #define preprocessor command.

Explain the difference and similarity between these two variables: char *String1; char String2[128];

1) the difference between this is the first one doesn't provide a size, while the limit is sat as 128 characters in the second one. 2) char *String1 gives the pointer to the starting of a character string. It will give the base to read the string whose staring is given by the declaration same way as the second one.

What gcc flag is used to link a particular library into a C program? Give an example.

1)The gcc -l flag is used to link a particular library in C program ex: gcc -static first.c -l math -o first

What are the four processes in converting a C program to an executable program? What are the formats of each stage's input and output files?

1)there are four stages to convert a C program to an executable program. The stages are preprocessing, compiling, assembly and linking. 2)Preprocessing is the first stage to make a program to executable. The C program input the preprocessor and generates the output for compiling. The output is a print.i file. The next step is compiling and this stage the input is print.i file and output will be print.s file. After that the next stage is assembly. Assembly stage Thales input print.s file. After assembling the program this stage generates the print.o file. The last stage is linking. The print.o file is input to this stage. The linker generates an executable file print. This is the final step of the converting a C program to executable.

What is the exact output from the following code? Indicate spaces with an upsidedown triangle. int i1 = 27; float f1 = 13.13; float f2 = -45.45; char data[] = "Bonzai!"; printf("%3d %7.3f %-10s %f %o\n",i1,f1,data,f2,i1);

27 13.130 Bonzai! -45.450001 33

What is an enumerated type?

An enumeration type is a set of identifiers called enumeration constants. enum [enumeration_tag] {<list of identifiers>} <variables>;

How are arrays treated differently from other variables when passed as arguments to functions?

Array names represent the address of the first element thus an array is passed by reference. All other types are passed by value.

Which of the following are keywords in C?

Auto, break, case, char, const, continue, default, do, double, else, enum, extern, float, for, goto, if, int, long, register, return, short , signed, sizeof, static, struct switch, typedef, union, unsigned, void, volatile, while

At what point during a program's execution are {automatic|external|static} variables initialized?

Automatic- variable come into existence on invocation. External- variables may be defined outside any function and then exist independently of the function. Static- variables in functions remain in existence even after the function has exited.

What does the following macro do? #define cc(A,B,C) (A)?(B):(C)

It defines the function cc s.t. if A is true it returns B if A is false it returns C.

What gcc flag is used to specify directories where include files might be found?

To find the directories where the include files are residing the gcc -L flag is used.

What is the output from the following program? #include <stdio.h> #include <string.h> int main(int argc,char *argv) { char Buffer[128],Data[128]; char *Offset; strcpy(Buffer,"What excellent stuffing"); Offset = strtok(Buffer," "); printf("%s\n",Buffer); Offset = strtok(NULL," "); strcpy(Data,Offset); printf("%s\n",Data+3); Offset = strtok(NULL," "); printf("%s\n",Offset); strncpy(Data,&Offset[3],3); printf("%s\n",Data); return(0); }

What ellent stuffing ffiellent

Give an example showing how an array of pointers can be used to create a two dimensional array in which the rows are of differing lenths.

char ** ptr = (char **)malloc(ARRAY_COLUMNS * sizeof(char *)); for(int i = 0; i < ARRAY_COLUMNS ; i++) { ptr[i] = (char *) malloc(ARRAY_ROWS * sizeof(char)); } Access will be with ptr[idx_of_row][idx_of_column] or with *(*(ptr + idx_of_row)) + idx_of_column)

What are the four basic data types of C?

char, int, float, double

Why should fgets be used in preference to gets?

fgets() is a safer version of gets() where you can provide limitation on input size. You can also decide to take input from which streams.

How are integer constants expressed using decimal, octal, and hexidecimal?

if an integer constant begins with 0x or 0X, it is hexadecimal. If it begins with the digit 0 it is octal. Otherwise it is assumed to be decimal.

Rewrite the following while loop as a for loop. Index = 1; while (Index < MAX) { printf("%d\n",Index); Total += Index; Index++; }

for(int Index=1;Index<Max; Index++) { printf("%d\n",Index); Total+=Index;}

Give an example showing how an array may be initialized when defined.

int number [4] = {[1],[2],[3],[4]};

Explain the difference between memcpy and memmove.

memcpy - Copy one buffer into another (bytewise version of strncpy). memmove - Moves a number of bytes from one buffer to another. Same as memcpy except the buffers may overlap.

Explain what realloc does, including the cases when the new size does not equal the old size.

realloc changes the size of a block of memory previously allocated with malloc or calloc whilst preserving the contents. Realloc returns a pointer to the new block or NULL if unsuccessful, in which case old is unchanged.

What does the & operator return when applied to a variable?

returns an address

What are the three predefined IO streams in UNIX, and what devices are they associated with by default?

stdin - initially associated with the keyboard stdout - initially associated with the screen. stderr - initially associated with he screen.

What effect does the const qualifier have when applied to a function argument?

the const cannot be modified.

Give typedefs to define a data type for an array of three pointers to functions, where each function takes two int arguments and returns a float. (OK, that's hard, I admit).

typedef(float(*CompareFunction)(intent))[3];

Explain the difference between a union and struct

with union you're only supposed to use on of the elements, because they're all stored at the same spot. A struct, has a separate memory location for each of its elements and they all can be used at once.


Related study sets

Chapter 17/Practice HW for Test #5/ Microbiology

View Set

what does it stand for????????????

View Set

Chapter #7 Review Questions [Macroeconomics]

View Set

Electrical Theory NCCER 26104-14

View Set

Cell Bio, Exam 4 (quiz questions/answers)

View Set

Principles of Management: Ch. 14 Quiz

View Set

Marketing, Advertising, and Social Media Compliance - 1

View Set

Fluid & Electrolyte Balance- RN PassPoint

View Set

CH #13 - Differential Analysis: The Key to Decision Making

View Set