Arrays and Pointers in C

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

Which of the following is a key difference between static and dynamic array initialization?

  • Dynamic arrays are stored in the stack while static arrays are stored in the heap.
  • Static arrays are initialized at runtime, while dynamic arrays are initialized at compile time.
  • Dynamic arrays require the use of `malloc` or `calloc` for memory allocation, whereas static arrays do not. (correct)
  • Static arrays can change size after initialization, while dynamic arrays cannot.

What is the primary risk associated with accessing an array element using an index that is out of bounds?

  • The program will automatically resize the array to accommodate the new index.
  • The array element will default to a null or zero value, preventing any issues.
  • The program will terminate with a specific 'out of bounds' error message.
  • It can lead to unpredictable behavior, such as reading from or writing to unintended memory locations. (correct)

In C, what is the purpose of the free() function when working with dynamic arrays?

  • It deallocates the memory that was previously allocated to the array, preventing memory leaks. (correct)
  • It increases the size of the dynamically allocated array.
  • It reinitializes all the elements of the array to zero.
  • It checks if the array is properly initialized.

What is the significance of the * operator in the context of C pointers?

<p>It is the dereference operator, used to access the value stored at the memory address pointed to by the pointer. (B)</p> Signup and view all the answers

Which step is missing from this sequence of actions required when using pointers? Declaration, Dereferencing, _________?

<p>Initialization (A)</p> Signup and view all the answers

Consider the following C code snippet: int arr2d[3][4];. How would you access the element in the second row and third column?

<p><code>arr2d[1][2]</code> (D)</p> Signup and view all the answers

Given int *ptr = NULL;, what is the most appropriate use for this pointer?

<p>To indicate that the pointer does not currently point to any valid memory location. (B)</p> Signup and view all the answers

What is the primary advantage of passing arguments to a function by reference rather than by value?

<p>It allows the function to modify the original variable directly, enabling changes to persist outside the function. (D)</p> Signup and view all the answers

How does recursion work?

<p>A function calling itself (D)</p> Signup and view all the answers

How does the calloc function differ from the malloc function in C?

<p><code>calloc</code> allocates memory and initializes it to zero, while <code>malloc</code> allocates memory without initializing it. (C)</p> Signup and view all the answers

Flashcards

What is an array?

A collection of items stored at contiguous memory locations.

Static Array Initialization

Defining and initializing an array at compile time.

Dynamic Array Initialization

Creating and initializing arrays during runtime, allowing for flexible size and memory allocation.

Bound checking

Ensuring array indices are within the defined range during access.

Signup and view all the flashcards

Out-of-bounds access

Accessing array elements outside the defined range leads to unpredictable results.

Signup and view all the flashcards

What is a pointer?

A variable that stores the memory address of another variable.

Signup and view all the flashcards

Pointer Declaration

Use the dereferencing operator (*) to declare a pointer.

Signup and view all the flashcards

malloc

Allocates uninitialized memory.

Signup and view all the flashcards

calloc

Allocates and initializes memory to zero.

Signup and view all the flashcards

free()

To release dynamically allocated memory.

Signup and view all the flashcards

Study Notes

  • Focus is on data structures, specifically arrays, pointers, and functions, including static and dynamic array initialization, bound checking, and the use of library vs user defined functions.

Arrays

  • Arrays are collections of items stored at contiguous memory locations
  • Arrays allow storing multiple values of the same type

Static Array Initialization

  • This refers to defining and initializing an array at compile time
  • Syntax: data_type array_name[array_size] = {value1, value2, ..., valueN};
  • Example: char letters[4] = {'A', 'B', 'C', 'D'};

Dynamic Array Initialization

  • This involves creating and initializing arrays at runtime, allowing flexibility in size and memory allocation
  • malloc: Allocates uninitialized memory
  • calloc: Allocates and initializes memory to zero
  • Free allocated memory using free(array_name) to avoid memory leaks
  • Syntax: data_type *array_name = (data_type *)malloc/calloc(array_size * sizeof(data_type));

Bound Checking

  • This refers to ensuring that array indices are within the defined range during access
  • Accessing array elements outside the defined range leads to unpredictable results
  • Accessing beyond array size example: int arr[5]; arr[10] = 20; leads to undefined behavior
  • Using negative indices example: arr[-1] = 30; leads to undefined behavior

2D Arrays in C

  • A 2D array is a data structure that stores elements in a tabular form, visualized as a grid or matrix with rows and columns
  • The syntax to declare a 2D array: data_type array_name[rows][columns];
  • Example: int matrix[3][4]; creates a 2D integer array with 3 rows and 4 columns
  • Initializing a 2D array requires assigning values to each element, enclosed in curly braces and separated by commas, in row-wise order
  • Row-wise initialization example: int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
  • Partial initialization example: int matrix[2][3] = {{1, 2}, {4, 5}};
  • Zero initialization example: int matrix[2][3] = {0};
  • To access a specific element in a 2D array, use square brackets with the row and column index:
  • Syntax: array_name[row_index][column_index]
  • Nested loops are used to process all elements in a 2D array, with the outer loop iterating through rows and the inner loop iterating through columns

Advantages and Limitations of 2D Arrays

  • Provide efficient storage and retrieval of data in tabular form
  • Size is fixed once declared and not easily expandable or resizable

Pointers

  • A pointer stores the memory address of other variables, functions, or even other pointers
  • The syntax for pointers is similar to variable declaration but uses the (*) dereferencing operator
  • Syntax: datatype * ptr; where ptr is the name of the pointer and datatype is the type of data it is pointing to
  • Declaring a pointer requires using the * dereference operator
  • Example: int *ptr; the declared pointer will point to a random memory address as it is not initialized, creating what is known as a wild pointer
  • Initializing a pointer assigns it an initial value, achieved by using the & (ampersand) addressof operator to get a variable's memory address
  • Example:
int var = 10;
int *ptr;
ptr = &var;
  • Dereferencing a pointer involves accessing the value stored in the memory address specified in the pointer

Advantages of Pointers

  • Used for dynamic memory allocation and deallocation
  • Arrays or structures can be accessed efficiently
  • Useful for accessing memory locations
  • Used to form complex data structures like linked lists, graphs, trees, etc
  • Reduce the program's length and execution time

Disadvantages of Pointers

  • Vulnerable to errors and can cause memory corruption if an incorrect value is provided
  • Can be complex to understand
  • Are majorly responsible for memory leaks in C
  • Comparatively slower than variables in C
  • Uninitialized pointers might cause a segmentation fault

Functions

  • Functions are blocks of statements that perform specific tasks
  • Contain programming statements enclosed by {}
  • Run when called
  • Accept data, known as parameters
  • Provide reusability and modularity
  • Can be called multiple times
  • The readability of code is improved
  • Functions enable the reuse the same body of code in any program without rewriting it
  • Debugging of the code be becomes easier
  • Code size is reduced, as duplicate sets of statements are replaced by function calls

Types of Functions

  • Library functions are declared in C header files, such as scanf(), printf(), sqrt(), pow(), strcat(), strlen(), etc
  • User-defined functions are created to reduce complexity and optimize code.
  • Defining user defined functions require 3 steps:
  • Function declaration or prototype
  • Function definition or body
  • Function call
  • Creating (declaring) own function syntax includes the function name, parentheses (), and curly brackets {}
    • Syntax: return_type function_name(parameter list) { // body of the function }
  • return_type is the data type of the value the function returns, or void if no value is returned
  • function_name is the actual name of the function
  • parameter list is placeholder, or optional
  • The function body contains statements that define what the function does
  • Function declarations inform the compiler about the function's name, number and type of arguments, and type of returned value
return_type functon_name(parameter list);
// Example Declaration:
int max(int num1, int num2);
int max(int, int);
  • Parameter names are not important when declaring a function, only types matter
  • To use a function, it must be called upon to perform task
  • A called function performs its defined task and returns program control to the main program when either the return statement is executed or the function-ending closing brace is reached
function_name (argument_list);

C Scope Rules

  • A scope is a region of the program where a defined variable can exist and be accessed
  • Variables in C can be declared in three places:
  • Inside a function or block and are called local variables
  • These variables can only be used by statements that are inside the function or block of code, and are not known to functions outside their own
#include <stdio.h>
int main ()
{
   /* local variable declaration */
   int a, b; int c;
   /* actual initialization */
   a = 10; b = 20; c = a + b;

   printf ("value of a = %d, b = %d and c = %d\n", a, b, c);

   return 0;
}
  • Outside of all functions and are called global variables
  • Global variables are defined and hold their values throughout the lifetime of the program
  • Accessing global variabes can occurr inside any of the functions defined for the program.
#include <stdio.h>

/* global variable declaration */
int g;

int main ()
{
  /* local variable declaration */
  int a, b;

  /* actual initialization */
  a = 10;
  b = 20;
  g = a + b;

  printf ("value of a = %d, b = %d and g = %d\n", a, b, g);

  return 0;
}
  • In the definition of function parameters and are called formal parameters

Passing Arguments to a Function

  • Arguments passed to a function can be "with arguments" or "without arguments"
  • When arguments are "with arguments", parameters must be declared, defined and have values that are passed during the function call.
  • Example Declaration: int sum (int x, int y);
  • Example Call: sum(10, 20);
  • When arguments are "without arguments", no parameters are included and no value is passed during the function call

Calling C Functions

  • C functions can be called in two ways:
    • Call by Value: A copy of the variable is passed to the function
    • Call by Reference: An address of the variable is passed to the function
  • In call by value method:
    • The value of the variable is passed to the function as a parameter, but is not modified
    • Different Memory is allocated for both actual and formal parameters
    • Actual parameter is the argument which is used in function call
    • Formal parameter is this the argument which is used in function definition
#include <stdio.h>
void swap(int, int); // function declaration

int main() {
  int a = 10;
  int b = 20;

  printf("Before swapping:a = %d, b = %d\n",a,b);
  swap(a,b);
  printf("In Final swapping: a = %d, b = %d\n",a,b);
  //Output In Final swapping: a = 10, b = 20
  return 0;
}

void swap (int a, int b) {
  int temp;

  temp = a;
  a=b;
  b=temp;
  printf("After swapping values in function a = %d, b = %d\n",a,b);
  //Output - After swapping values in function a = 20, b = 10
}
// Output - Before swapping:a = 10, b = 20
  • In call by reference method, the address of the variable is passed to the function as a parameter, and can be modified
    • Same memory is used for both actual and formal parameters
#include <stdio.h>
void swap(int *, int *); //prototype of the function

int main() {
  int a = 10;
  int b = 20;

  printf("Before swapping the values in main a = %d, b = %d\n",a,b);
  swap(&a,&b);
  printf("After swapping values in main a = %d, b = %d\n",a,b);
  // Output - After swapping values in main a = 20, b = 10

  return 0;
}

void swap (int *a, int *b) {
  int temp;

  temp = *a;
- a=*b;
- b=temp;

  printf("After swapping values in function a = %d, b = %d\n",*a,*b);
  //After swapping values in function a = 20, b = 10
}

Recursion

  • Recursion is a process where a function calls a copy of itself to work on a smaller problem
  • Any function calling itself is called a recursive function, and such calls are called recursive calls
  • Recursion involves several recursive calls
  • It is important to impose a termination condition of recursion
  • Recursion is useful for tasks that can be defined in terms of similar subtasks like sorting, searching, and traversal problems
void recursion() {
  recursion(); // call to self
}

int main() {
  recursion();
}
  • The function calls itself continuously
  • Must define exit for function
int fact (int n) {
  if (n>=1) {
     return n*fact(n-1);
  } else {
    return 1;
  }
}

int main() {
  int n;
  printf("Enter a positive integer: ");
  scanf("%d",n);
  printf("Factorial of %d = %d", n,fact(n));
  return 0;
}

Types of Storage Classes

  • There exist four types of storage classes in C:
  • Automatic storage class
  • Keyword: auto
  • Storage: memory
  • Default initial value: garbage value
  • Scope: local to the block in which the variable is defined
  • Life: till the control remains within the block in which the variable is defined
#include<stdio.h>
#include<conio.h>

void main() {
  auto int i=1;

  printf("auto int= 1 - scope outside inner curly brackets:\n");
  printf("%d\t", i);

  {
    auto int i=2;

    printf("auto int= 2 - scope inside outer curly brackets:\n");
    printf("%d\t", i);

    {
      auto int i=3;
      printf("auto int= 3 - scope inside inner curly brackets:\n");
      printf("%d\t", i);
    }
  }
  getch();
}
//Result: 1 2 3
  • Register storage class
  • Keyword: register
  • Storage: CPU Register
  • Default initial value: garbage value
  • Scope: local to the block in which the variable is defined
  • Life: till the control remains within the block in which the variable is defined
#include <stdio.h>
#include <conio.h>

void main() {
  register int i;
  printf ("Registers: \n")
  for(i=1; i <=10; i++){
    printf("%d\t",i);
  }
  getch();
}
//Result: 1 2 3 4 5 6 7 8 9 10
}
  • Static storage class
  • Keyword: static
  • Storage: memory
  • Default initial value: zero
  • Scope: local to the block in which the variable is defined
  • Life: value of the variable persists between different function calls
#include <stdio.h>
#include <conio.h>

void increment() {
  static int a =1;
  printf ("Static: \n");
  printf("%d\t",a);
  a = a + 1;
}

void main() {
  increment();
  increment();
  increment();
  getch();
}
//Output: 1 2 3
}
  • External storage class
  • Keyword: extern
  • Storage: memory
  • Default initial value: zero
  • Scope: global
  • Life: as long as the program's execution doesn't come to an end
#include <stdio.h>
#include <conio.h>

int a =1;

void increment() {
  printf ("Extern: \n");
  a = a + 1;
  printf("%d\t",a);
}

void main() {
  printf("%d\t",a);
  increment();
  increment();
  getch();
}
//Output: 1 2 3

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

More Like This

Use Quizgecko on...
Browser
Browser