💻 Unit 3 – Part A (2-Mark Q&A)

Programming in C

⬅ Back to Unit 3

Ad Space

Part A: Functions & Pointers

17) Significance of a function prototype in C

A prototype declares name, return type, and parameter types/order to the compiler. It enables type checking of calls, correct implicit conversions, and allows calling a function before its definition or from other files.

int sum(int a, int b);  // prototype
int main(){ printf("%d", sum(3,4)); } 
int sum(int a,int b){ return a+b; }

Without a prototype, mismatched arguments may compile but cause undefined behavior.

18) Dynamic memory allocation – concept

Allocates memory at runtime from the heap when exact size is unknown at compile time. Use malloc(), calloc(), realloc(), and always free with free().

#include <stdlib.h>
int *arr = malloc(n * sizeof *arr);     // allocate n ints
if(!arr){ /* handle error */ }
arr = realloc(arr, m * sizeof *arr);    // resize to m
free(arr);                              // release

calloc zero-initializes; malloc leaves memory indeterminate.

19) When is a NULL pointer used?

Node *head = NULL;                // empty list
int *p = malloc(100*sizeof *p);
if(p == NULL){ /* allocation failed */ }

20) Usage/advantages of functions

double area(double r){ return 3.14159*r*r; }

21) Built-in vs User-defined functions

#include <string.h>  // built-in
size_t n = strlen("C");
int max2(int a,int b){ return a>b?a:b; } // user-defined

22) What is call by reference?

Passing the address of variables (via pointers) so the callee can modify the caller’s originals. Use unary * to dereference inside the function.

void swap(int *x,int *y){ int t=*x; *x=*y; *y=t; }
int a=5,b=7; swap(&a,&b); // a=7,b=5

Contrast: call by value passes copies; originals unchanged.

23) Define a pointer & how to declare

A pointer stores the memory address of another object/function. Declaration uses * with a base type.

int *pi;    // pointer to int
char *pc;   // pointer to char
int **ppi;  // pointer to pointer to int
int x=10; pi=&x;   // pi points to x; *pi == 10

Type of pointer must match the pointed-to type (except void* which is generic address).

24) What are library functions?

Pre-written, optimized functions from the C Standard Library. Include the right header, link with the standard library, and call.

#include <math.h>
double r = sqrt(49.0);   // 7.0

Benefits: correctness, portability, and performance.

Ad Space