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?

  • Static initialization allows modification of array size during runtime, while dynamic does not.
  • Dynamic initialization uses less memory than static initialization.
  • Static initialization happens at compile time, while dynamic occurs during runtime. (correct)
  • Dynamic initialization happens at compile time, while static occurs during runtime.

What could be the consequence of not performing bound checking when working with arrays?

  • Unpredictable behavior due to accessing memory outside the array's bounds. (correct)
  • Memory leaks from unreleased allocated space.
  • The program will terminate with a specific error message.
  • Slower program execution due to extra checks.

Given the declaration int arr[5][3];, how would you access the element in the second row and third column (assuming zero-based indexing)?

  • arr[1][2] (correct)
  • arr[2][3]
  • arr[2][1]
  • arr[3][5]

Consider int *ptr;. What is the primary purpose of the * in this declaration?

<p>To indicate that <code>ptr</code> is a pointer variable that will store the address of an integer variable. (D)</p> Signup and view all the answers

What is the significance of using free(array_name) after dynamic array allocation?

<p>It releases the dynamically allocated memory, preventing memory leaks. (A)</p> Signup and view all the answers

Which of the following best describes the difference between malloc and calloc?

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

What happens if you try to access arr[-1] of an array int arr[5]?

<p>It leads to undefined behavior, potentially accessing memory outside the array's bounds. (D)</p> Signup and view all the answers

Given int *ptr = NULL; int var = 10; ptr = &var;, what does *ptr represent?

<p>The value of <code>var</code> (which is 10). (C)</p> Signup and view all the answers

What is the role of the ampersand & operator when used with a variable?

<p>It returns the memory address of the variable. (B)</p> Signup and view all the answers

When passing arguments to a function 'by reference', what is actually being passed?

<p>A pointer to the memory location of the variable. (A)</p> Signup and view all the answers

Flashcards

What is an Array?

A collection of items stored at contiguous memory locations, allowing storage of multiple values of the same type.

Static Array Initialization

Defining and initializing an array at compile time.

Dynamic Array Initialization

Creating and initializing arrays at runtime, allowing flexibility in size and memory allocation.

Bound Checking

Ensuring that array indices are within the defined range during access to prevent unpredictable results.

Signup and view all the flashcards

What does a pointer store?

Memory address of a variable.

Signup and view all the flashcards

What operator is used in pointer declaration?

The * symbol.

Signup and view all the flashcards

What are the steps for using pointers in C?

Declare, Initialize and Dereference.

Signup and view all the flashcards

What does malloc do?

Allocates memory but doesn't initialize it.

Signup and view all the flashcards

What does calloc do?

Allocates memory and initializes it to zero.

Signup and view all the flashcards

What does free() do?

Releases previously allocated memory, preventing memory leaks.

Signup and view all the flashcards

Study Notes

Arrays

  • Arrays are collections of items stored at contiguous memory locations.
  • Arrays facilitate storing multiple values of the same data type.
  • An example of an array would be: int numbers[5];

Static Array Initialization

  • Static Array Initialization is defining and initializing an array at compile time.
  • The syntax is: data_type array_name[array_size] = {value1, value2, ..., valueN};
  • For example: char letters[4] = {'A', 'B', 'C', 'D'};

Dynamic Array Initialization

  • Dynamic Array Initialization involves creating and initializing arrays at runtime, providing flexibility in size and memory allocation.
  • malloc allocates uninitialized memory.
  • calloc allocates and initializes memory to zero.
  • Remember to free allocated memory using free(array_name) to avoid memory leaks.
  • The syntax for allocation is: data_type *array_name = (data_type *)malloc/calloc(array_size * sizeof(data_type));

Array Bound Checking

  • Bound checking makes sure that array indices are within the defined range during access.
  • Accessing array elements outside the defined range leads to unpredictable results.
  • Example: int arr[5]; arr[10] = 20; // Undefined behavior
  • Negative indices can also cause issues: arr[-1] = 30; // Undefined behavior

2D Arrays in C

  • A 2D array is a data structure that stores elements in a tabular form.
  • In C, a 2D array can be visualized as a grid or a matrix with rows and columns.

Declaring 2D Arrays

  • When declaring an array, specify the data type, the name of the array, the amount of rows, and the amount of columns.
  • The syntax is: data_type array_name[rows][columns];
  • For instance, int matrix[3][4]; creates a 2D integer array called "matrix" with 3 rows and 4 columns.

Initializing 2D Arrays

  • A 2D array has to be initialized when declared in C or the values won't be assigned.
  • The values are to be seperated by commas and enclosed inside of curly brackets.
  • The command of initialization has to be row-wise, starting from the top left.
  • Row-wise initialization would look like: int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
  • Partial initialization is when you don't input the values and it looks like: int matrix[2][3] = {{1, 2}, {4, 5}};
  • Zero initialization would look like: int matrix[2][3] = {0};

Accessing Elements in 2D Arrays

  • To access a specific elemtn in a 2D array, you need to provide the row and column index inside square brackets.
  • The syntax is: array_name[row_index][column_index]
  • Indexing starts from 0.

Traversing 2D Arrays

  • The use of a nested loops is needed when processing elements inside a 2D array.
  • The outer loop will iterate through rows, and the inner loop iterates through columns.

Advantages of 2D Arrays

  • Features efficient storage and retrieval of data in tabular form.

Limitations of 2D Arrays

  • It has a fixed size once declared, and isn't easily expandable or resizable.

Pointers

  • A pointer stores the memory address of other variables, functions, or other pointers.

Pointer Syntax

  • The syntax is like the variable declaration in C, but uses the dereferencing operator (*).
  • The syntax looks like: datatype * ptr;
  • Where ptr is the name of the pointer.
  • Where datatype the type of data that's being pointed to.

Steps for Using Pointers

  • Pointer Declaration
  • Pointer Initialization
  • Pointer Dereferencing

Pointer Declaration

  • Dereference operator (*) is used before the name.
  • Example: int *ptr;
  • Pointers point to random memory addresses if they aren't initialized, this makes them wild pointers.

Pointer Initialization

  • This is the process of assigning a value to a pointer variable.
  • Usually involving the ampersand (&) and the addressof operator to get the memory address of a variable, which is then stored under the pointer variable.
  • Example: `int var = 10; int *ptr; ptr = &var;

Pointer Dereferencing

  • This is the process of accessing the value stored in the memory address specified in the pointer.

Advantages of Pointers

  • They are used for dynamic memory allocation and deallocation.
  • Arrays or structures can be efficiently accessed with pointers.
  • Pointers are useful for accessing memory locations.
  • They form complex data structures like linked lists, graphs, and trees.
  • They also reduce both the length of the program and its execution time.

Disadvantages of Pointers

  • They are vulnerable to errors.
  • Memory corruption occurs if an incorrect value is provided to pointers.
  • Pointers are complex to understand.
  • Pointers are majorly responsible for memory leaks in C.
  • Pointers are slower than variables in C.
  • Uninitialized pointers might cause a segmentation fault.

Functions

  • A function is a block of statements that performs a specific task.
  • It contains a set of programming statements enclosed by curly brackets {}.
  • A function is a block of code which only runs when it is called.
  • Data, known as parameters, can be passed into a function.
  • Functions are called multiple times to provide reusability and modularity to the C program.

Need for Functions

  • To improve the readability of code.
  • Improves the reusability of the code; the same function can used in any program rather than writing the same code from scratch.
  • Debugging of the code made easier, as errors are easy to be traced.
  • Reduces the size of the code, duplicate set of statements are replaced by function calls.

Function Types

  • Library Functions: These functions are declared in the C header files, such as scanf(), printf(), sqrt(), and pow().
  • User-defined functions: Functions created by the programmer, reducing complexity and optimizing code.

User Defined Functions

  • In order to define user defined functions, follow 3 steps:
  • Declare the function.
  • Define the function
  • Call the function.

Declaring a Function

  • To create or declare a function, specify the name of the function, followed by parentheses () and curly brackets {}
  • return_type function_name(parameter list) { // body of the function }
  • return_type is the data type of the value the function returns.
  • Some functions perform operations without returning a value; in this case, return_type is the keyword void.
  • function name is the actual name, along with the parameter list

Declaring Parameters

  • A parameter is a placeholder where when a function is invoked, its passes a value to the parameter.
  • This value is called the actual parameter or the argument and the parameter's type
  • Parameters are optional; a function might not contain any parameters.
  • Function body contains statements defining what the function does.

Function Declarations

  • A function declaration tells the compiler both a function name and how the function is called.
  • Function declarations also allow their body to be defined separately.
  • The syntax is: return_type function_name (parameter list);
  • Example: int max(int num1, int num2);
  • Parameter names are not that critical in function declarations, just their type.

Calling a Function

  • When creating a C function, there has to be a give a solid definition of what the function has to do.
  • Functions will have to be called to perform its task.
  • Program controll passes off to the called function when it is summoned.

Function Syntax and Return

  • When a defined task has been performed, if the return statement is executed or its function ending closing bracket reached, the called function returns to the main program.
  • function_name (argument_list);

SCOPE Rules

  • A scope is a region of the program where a variable can have its existence.
  • Variables are declared in 3 spots:
  • Inside a function or a block (local variables).
  • Outside of all functions (global variables).
  • In the definition of function parameters (formal parameters).

Local Variables

  • Variables are called locals if they get declared inside a function or block.
  • Local variables can only be used by the statements inside said function or block of code.

Global Variables

  • Global variables are defined outside a function, usually on top of the program.
  • These variables hold their values across the lifetime of the program.

Passing Function Arguments

  • With Arguments: Declared and defined with parameter list, values for parameter passed during call.
  • With Arguments declared as: int sum (int x, int y)
  • With Out arguments: No parameters are included.

Calling C Functions

  • C functions are called 2 ways in a program.
  • Call by value: copy of the variable is passed to the function.
  • Call by reference: An address of the variable is passed to the function.

Call by Value

  • With Call by value method, the value of the variable is the parameter passed in the function.
  • Value of the actual parameter can't be modified by its formal parameter because value of actual parameter copies over to formal parameters.
  • This will make a different memory allocation of both actual and formal parameters.

Call by Reference

  • The address of the variable has to be a passed in in call by referance.
  • Making it so actual parameter can be modified by formal parameter. Same memory is used for both actual and formal parameters since both only use the address.

Recursion

  • This is the process that happens when a function calls a copy of itself in order to work on a smaller problem.
  • Functions are called recurive functions if it does call itself, and such is known as recursive calls.
  • Important recursion has a terimation condition.
  • Recursion may be applied to sorting, searching, and traversal problems.
  • If a program allows you to call a function inside the same function, then it will be recursive.

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

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

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

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

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