Lecture 3 - Pointers, Arrays, Strings and Dynamic Memory Allocation Flashcards
What is a pointer in C?
A pointer is a variable that stores the memory address of another variable. It is declared using the *
symbol.
int *ptr;
How do you declare a pointer to an integer in C?
int *ptr;
This declares ptr
as a pointer to an int
.
How do you get the address of a variable in C?
The address of a variable can be obtained using the &
operator.
int x = 10; int *ptr = &x;
How do you dereference a pointer in C?
Dereferencing a pointer is done using the *
operator to access the value stored at the memory address.
int x = 10; int *ptr = &x; int y = *ptr; // y gets the value 10
What is pointer arithmetic in C?
Pointer arithmetic allows you to increment or decrement pointers. When you increment a pointer, it moves by the size of the data type it points to.
int arr[5] = {1, 2, 3, 4, 5}; int *ptr = arr; ptr++; // Now points to the second element
How is an array different from a pointer in C?
An array is a fixed-size sequence of elements, whereas a pointer can point to any memory location. However, the name of an array acts like a pointer to the first element.
What is the relationship between arrays and pointers in C?
The name of an array is a pointer to its first element. For example, if arr
is an array, arr
is equivalent to &arr[0]
.
How do you declare and initialize an array in C?
int arr[5] = {1, 2, 3, 4, 5};
What is a string in C?
A string in C is an array of characters terminated by a null character '\0'
. Strings are stored as char[]
or char*
.
How do you declare and initialize a string in C?
char str[] = "Hello, World!";
This creates a string with the value "Hello, World!"
and an implicit null terminator '\0'
.
What is malloc
and how is it used in C?
malloc
is used to dynamically allocate memory at runtime. It returns a pointer to the allocated memory.
int *arr = (int*)malloc(5 * sizeof(int));
How do you access individual characters in a string?
Strings are arrays of characters, so you can access individual characters using array notation.
char str[] = "Hello"; char first_char = str[0]; // 'H'
What is free
and why is it used?
free
is used to release memory that was previously allocated using malloc
, calloc
, or realloc
.
free(arr);
What is calloc
and how is it different from malloc
?
calloc
allocates memory for an array of elements and initializes all the bytes to zero. Unlike malloc
, it takes two arguments (number of elements and size of each element).
int *arr = (int*)calloc(5, sizeof(int));
What is the purpose of realloc
in C?
realloc
is used to resize a previously allocated memory block.
arr = (int*)realloc(arr, 10 * sizeof(int));