Master’s Admission Preparation Batch Lecture Note=4
Lecture Note -04
C Programming-4
C Pointers
we can get the memory address of a variable with the reference operator &:
Example
int myAge = 43; // an int variable
printf("%d", myAge); // Outputs the value of myAge (43)
printf("%p", &myAge); // Outputs the memory address of myAge (0x7ffe5367e044)
A pointer is a variable that stores the memory address of another variable as its value.
A pointer variable points to a data type (like int) of the same type, and is created with the *
operator.
The address of the variable you are working with is assigned to the pointer:
Example
int myAge = 43; // An int variable
int* ptr = &myAge; // A pointer variable, with the name ptr, that stores the address of myAge
// Output the value of myAge (43)
printf("%d\n", myAge);
// Output the memory address of myAge (0x7ffe5367e044)
printf("%p\n", &myAge);
// Output the memory address of myAge with the pointer (0x7ffe5367e044)
printf("%p\n", ptr);
Create a pointer variable with the name ptr, that points to an int variable (myAge). Note that
the type of the pointer has to match the type of the variable you're working with (int in our
example).
Use the & operator to store the memory address of the myAge variable, and assign it to the
pointer.
Now, ptr holds the value of myAge's memory address.
How pointer works
#include <stdio.h>
int main()
{
// Normal Variable
int var = 10;
// Pointer Variable ptr that stores address of var
int *ptr = &var;
// Directly accessing ptr will give us an address
printf("%d", ptr);
Page 1 of 14
Group: BUET DU CSE MSc Admission Preparation Muhammad Aminul Islam
Master’s Admission Preparation Batch Lecture Note=4
return 0;
}
Output
1751215308
This hexadecimal integer (starting with 0x) is the memory address.
Initialize the Pointer
• A pointer is initialized by assigning it the address of a variable using the address
operator (&).
• Syntax: pointer_name = &variable;
• Initializing a pointer ensures it points to a valid memory location before use.
• You can also initialize a pointer to NULL if it doesn’t point to any variable yet: int *ptr
= NULL;
Dereference
In the example above, we used the pointer variable to get the memory address of a variable
(used together with the & reference operator).
You can also get the value of the variable the pointer points to, by using the * operator (the
dereference operator):
Example
int myAge = 43; // Variable declaration
int* ptr = &myAge; // Pointer declaration
// Reference: Output the memory address of myAge with the pointer (0x7ffe5367e044)
printf("%p\n", ptr);
// Dereference: Output the value of myAge with the pointer (43)
printf("%d\n", *ptr);
Note that the * sign can be confusing here, as it does two different things in our code: When
used in declaration (int* ptr), it creates a pointer variable. When not used in declaration, it act
as a dereference operator.
Good To Know: There are two ways to declare pointer variables in C:
Page 2 of 14
Group: BUET DU CSE MSc Admission Preparation Muhammad Aminul Islam
Master’s Admission Preparation Batch Lecture Note=4
int* myNum;
int *myNum;
Size of Pointers
The size of a pointer in C depends on the architecture (bit system) of the machine, not the data
type it points to.
On a 32-bit system, all pointers typically occupy 4 bytes.
On a 64-bit system, all pointers typically occupy 8 bytes.
The size remains constant regardless of the data type (int*, char*, float*, etc.). We can verify
this using the sizeof operator.
#include <stdio.h>
int main() {
int *ptr1;
char *ptr2;
// Finding size using sizeof()
printf("%zu\n", sizeof(ptr1));
printf("%zu", sizeof(ptr2));
return 0;
}
Output
8
8
The reason for the same size is that the pointers store the memory addresses, no matter what
type they are. As the space required to store the addresses of the different memory locations is
the same, the memory required by one pointer type will be equal to the memory required by
other pointer types.
Note: The actual size of the pointer may vary depending on the compiler and system
architecture, but it is always uniform across all data types on the same system.
Notes on Pointers
Pointers are one of the things that make C stand out from other programming languages, like
Python and Java.
They are important in C, because they allow us to manipulate the data in the computer's
memory. This can reduce the code and improve the performance. If you are familiar with data
structures like lists, trees and graphs, you should know that pointers are especially useful for
implementing those. And sometimes you even have to use pointers, for example when
working with files and memory management.
But be careful; pointers must be handled with care, since it is possible to damage data stored in
other memory addresses.
Page 3 of 14
Group: BUET DU CSE MSc Admission Preparation Muhammad Aminul Islam
Master’s Admission Preparation Batch Lecture Note=4
Pointer to Pointer
You can also have a pointer that points to another pointer. This is called a pointer to pointer
(or "double pointer").
It might sound confusing at first, but it's just one more level of indirection: a pointer that stores
the address of another pointer.
Think of it like this: A normal pointer is like a note with an address on it. A pointer to pointer
is like another note telling you where that first note is kept.
Note: Pointer to pointer is not something you need to use often as a beginner. However, you
might see it in more advanced programs, so it's good to understand what it means and how it
works.
Let's look at a simple example to understand how this works:
Example
int myNum = 10; // normal variable
int *ptr = &myNum; // pointer to int
int **pptr = &ptr; // pointer to pointer
printf("myNum = %d\n", myNum);
printf("*ptr = %d\n", *ptr);
printf("**pptr = %d\n", **pptr);
Result:
myNum = 10
*ptr = 10
**pptr = 10
Here's what happens step by step:
• myNum holds the value 10.
• ptr holds the address of myNum.
• pptr holds the address of ptr.
• *ptr gives the value of myNum.
• **pptr also gives the value of myNum, by going through both pointers.
So:
• *ptr = value of myNum
• **pptr = value of myNum through both levels
Changing Values Through a Pointer to Pointer
Since **pptr accesses the original variable, you can use it to change the value of the variable
too:
Example
int myNum = 5;
int *ptr = &myNum;
int **pptr = &ptr;
**pptr = 20; // changes myNum
printf("myNum = %d\n", myNum); // prints 20
Page 4 of 14
Group: BUET DU CSE MSc Admission Preparation Muhammad Aminul Islam
Master’s Admission Preparation Batch Lecture Note=4
Another example for practice
#include <stdio.h>
int main() {
int var = 10;
// Pointer to int
int *ptr1 = &var;
// Pointer to pointer (double pointer)
int **ptr2 = &ptr1;
// Accessing values using all three
printf("var: %d\n", var);
printf("*ptr1: %d\n", *ptr1);
printf("**ptr2: %d", **ptr2);
return 0;
}
Summary
• A pointer to pointer stores the address of another pointer.
• *ptr gives the value of a variable.
• **pptr gives the same value by following two levels of indirection.
• They can be useful when passing pointers to functions or working with complex data
structures.
Advantages of Pointers
Following are the major advantages of pointers in C:
• Pointers are used for dynamic memory allocation and deallocation.
• An Array or a structure can be accessed efficiently with pointers
• Pointers are useful for accessing memory locations.
• Pointers are used to form complex data structures such as linked lists, graphs, trees, etc.
• Pointers reduce the length of the program and its execution time as well.
Issues with Pointers
Pointers are vulnerable to errors and have following disadvantages:
• Memory corruption can occur if an incorrect value is provided to pointers.
• Pointers are a little bit complex to understand.
• Pointers are majorly responsible for memory leaks in C.
• Accessing using pointers are comparatively slower than variables in C.
• Uninitialized pointers might cause a segmentation fault.
Common mistakes when working with pointers
Suppose, you want pointer pc to point to the address of c. Then,
int c, *pc;
Page 5 of 14
Group: BUET DU CSE MSc Admission Preparation Muhammad Aminul Islam
Master’s Admission Preparation Batch Lecture Note=4
// pc is address but c is not
pc = c; // Error
// &c is address but *pc is not
*pc = &c; // Error
// both &c and pc are addresses
pc = &c; // Not an error
// both c and *pc are values
*pc = c; // Not an error
Here's an example of pointer syntax beginners often find confusing.
#include <stdio.h>
int main() {
int c = 5;
int *p = &c;
printf("%d", *p); // 5
return 0;
}
Why didn't we get an error when using int *p = &c;?
It's because
int *p = &c;
is equivalent to
int *p;
p = &c;
In both cases, we are creating a pointer p (not *p) and assigning &c to it.
To avoid this confusion, we can use the statement like this:
int* p = &c;
int i = 10;
int *p = &i;
int **q = &p;
int ***r = &q;
What will be printed in each of the following cases?
a. printf(“%d”, *p)
b. printf(“%d”, *q)
c. printf(“%d”, *r)
d. printf(“%d”, **p)
e. printf(“%d”, **r)
a. 10
b. garbage
c. garbage
d. error (cause there’s no pointer declare as **p)
e. garbage
Page 6 of 14
Group: BUET DU CSE MSc Admission Preparation Muhammad Aminul Islam
Master’s Admission Preparation Batch Lecture Note=4
#include<stdio.h>
int main()
{
}
int i=10;
int *p=&i;
int **q=&p;
int ***r=&q;
printf("%d\n",**p);
printf("%d\n",**q);
printf("%d\n",***r);
printf("%d\n",***p);
printf("%d\n",&i);
Ans a: Code-Error
Ans b: 10
Ans c: 10
Ans d: Code-Error
Ans e: Address of i
C Dynamic Memory Allocation
As you know, an array is a collection of a fixed number of values. Once the size of an array is
declared, you cannot change it. Sometimes the size of the array you declared may be
insufficient. To solve this issue, you can allocate memory manually during run-time. This is
known as dynamic memory allocation in C programming.
To allocate memory dynamically, library functions are malloc(), calloc(), realloc() and free()
are used. These functions are defined in the <stdlib.h> header file.
C malloc()
The name "malloc" stands for memory allocation.
The malloc() function reserves a block of memory of the specified number of bytes. And, it
returns a pointer of void which can be casted into pointers of any form.
Syntax of malloc()
ptr = (castType*) malloc(size);
Example
ptr = (float*) malloc(100 * sizeof(float));
The above statement allocates 400 bytes of memory. It's because the size of float is 4 bytes.
And, the pointer ptr holds the address of the first byte in the allocated memory.
The expression results in a NULL pointer if the memory cannot be allocated.
Page 7 of 14
Group: BUET DU CSE MSc Admission Preparation Muhammad Aminul Islam
Master’s Admission Preparation Batch Lecture Note=4
C calloc()
The name "calloc" stands for contiguous allocation.
The malloc() function allocates memory and leaves the memory uninitialized, whereas the
calloc() function allocates memory and initializes all bits to zero.
Syntax of calloc()
ptr = (castType*)calloc(n, size);
Example:
ptr = (float*) calloc(25, sizeof(float));
The above statement allocates contiguous space in memory for 25 elements of type float.
C realloc()
If the dynamically allocated memory is insufficient or more than required, you can change the
size of previously allocated memory using the realloc() function.
Syntax of realloc()
ptr = realloc(ptr, x);
Here, ptr is reallocated with a new size x.
C free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on
their own. You must explicitly use free() to release the space.
Syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
What are the basic differences between call by value and call by reference? Explain with
appropriate examples.
Call by value: Call by value actually deals with the value of the variable. It does not deal with
the address of the variable. That’s why, Function is called by the variable’s value. So, it cannot
change variable’s value. As example:
#include<stdio.h>
void set(int x) {
x=20;
}
int main()
{
int i=10;
set(i); // set(10)
printf("the value of i is = %d",i);
return 0;
Page 8 of 14
Group: BUET DU CSE MSc Admission Preparation Muhammad Aminul Islam
Master’s Admission Preparation Batch Lecture Note=4
}
The output of this code : The value of i is=10.
Call by Reference: Call By reference always deals with the address of the variable. Not its
value. As example:
#include<stdio.h>
void set(int *x) // x=&i, x points to the adress of i
{
*x=20;
}
int main()
{
int i=10;
set(&i); // address of i
printf("the value of i is = %d",i);
return 0;
}
The output of this code is: the value of I is = 20. As it deals with the address of the variable. So
by pointer, in the function the value of I is changed!
Create a File
To create a file, you can use the w mode inside the fopen() function.
The w mode is used to write to a file. However, if the file does not exist, it will create one for
you:
Example
FILE *fptr;
// Create a file
fptr = fopen("[Link]", "w");
// Close the file
fclose(fptr);
Tip: If you want to create the file in a specific folder, just provide an absolute path (remember
to use double backslashes to create a single backslash (\), like we specified in strings special
characters):
fptr = fopen("C:\\directoryname\\[Link]", "w");
Write To a File
Let's use the w mode from the previous chapter again, and write something to the file we just
created.
Page 9 of 14
Group: BUET DU CSE MSc Admission Preparation Muhammad Aminul Islam
Master’s Admission Preparation Batch Lecture Note=4
The w mode means that the file is opened for writing. To insert content to it, you can use the
fprintf() function and add the pointer variable (fptr in our example) and some text:
Example
FILE *fptr;
// Open a file in writing mode
fptr = fopen("[Link]", "w");
// Write some text to the file
fprintf(fptr, "Some text");
// Close the file
fclose(fptr);
Note: If you write to a file that already exists, the old content is deleted, and the new content is
inserted. This is important to know, as you might accidentally erase existing content.
For example:
fprintf(fptr, "Hello World!");
As a result, when we open the file on our computer, it says "Hello World!" instead of "Some
text":
Write a C program to read from [Link] and count the number of vowels.
#include <stdio.h>
#include <ctype.h> // Required for the tolower() function
int main() {
FILE *fptr;
char ch;
int count = 0;
// Open the file "[Link]" in read mode ("r")
fptr = fopen("[Link]", "r");
// Check if the file exists
if (fptr == NULL) {
printf("Error: Could not open file.\n");
return 1;
}
// Read character by character until the End Of File (EOF)
while ((ch = fgetc(fptr)) != EOF) {
// Convert character to lowercase to handle both 'A' and 'a' easily
char lowerCh = tolower(ch);
// Check if the character is a vowel
Page 10 of 14
Group: BUET DU CSE MSc Admission Preparation Muhammad Aminul Islam
Master’s Admission Preparation Batch Lecture Note=4
if (lowerCh == 'a' || lowerCh == 'e' || lowerCh == 'i' ||
lowerCh == 'o' || lowerCh == 'u') {
count++;
}
}
// Close the file pointer to free up resources
fclose(fptr);
// Display the final result
printf("Total number of vowels: %d\n", count);
return 0;
}
Write a C program to append the content of [Link] to [Link], and then copy the entire
content of [Link] into [Link].
#include<stdio.h>
int main()
{
FILE *r,*w;
r=fopen("[Link]","r");
w=fopen("[Link]","a");
char ch;
while((ch=fgetc(r))!=EOF)
{
fputc(ch,w);
}
fclose(r);
fclose(w);
r=fopen("[Link]","r");
w=fopen("[Link]","w");
while((ch=fgetc(r))!=EOF)
{
fputc(ch,w);
}
fclose(r);
fclose(w);
return 0;
}
Page 11 of 14
Group: BUET DU CSE MSc Admission Preparation Muhammad Aminul Islam
Master’s Admission Preparation Batch Lecture Note=4
Write a C code that will copy the contents of File1 into File2 then concatenate File3 with
File2. So, File2 is the output file. For example, [Link]=” hello world”, [Link]=” hello cse”.
Then [Link] will be “hello world hello cse”. [ first copy then concatenate]
#include<stdio.h>
int main()
{
/************** Part one ***************/
FILE *r,*w;
r=fopen("[Link]","r");
w=fopen("[Link]","w");
char ch[100];
while(!feof(r))
{
fgets(ch,100,r);
fputs(ch,w);
}
fclose(r);
fclose(w);
/************* Part two ****************/
r=fopen("[Link]","r");
w=fopen("[Link]","a");
while(!feof(r))
{
fgets(ch,100,r);
fputs(ch,w);
}
fclose(r);
fclose(w);
return 0;
}
C strcmp()
In C, strcmp() is a built-in library function used to compare two strings lexicographically. It
takes two strings (array of characters) as arguments, compares these two strings
lexicographically, and then returns some value as a result.
The strcmp function in C is used to compare two strings, with syntax: int strcmp(const char
*str1, const char *str2);, where str1 and str2 are the strings to compare.
It returns 0 if the strings are equal, a negative value if str1 is less than str2, and a positive value
if str1 is greater than str2.
#include <stdio.h>
Page 12 of 14
Group: BUET DU CSE MSc Admission Preparation Muhammad Aminul Islam
Master’s Admission Preparation Batch Lecture Note=4
#include <string.h>
int main(){
char* s1 = "Aziz";
char* s2 = "Aziz";
// Printing the return value of the strcmp()
printf("%d", strcmp(s1, s2));
return 0;
}
Output
0
Explanation: In this code, two strings, s1 and s2, are declared with the same value "Aziz". The
strcmp() function compares these two strings and returns 0 since they are identical.
How strcmp() works?
C strcmp() function works by comparing the two strings lexicographically. It means that it
compares the ASCII value of each character till the non-matching value is found or the NULL
character is found. The working of the C strcmp() function can be described as follows:
1. It starts with comparing the ASCII values of the first characters of both strings.
2. If the first characters in both strings are equal, then this function will check the second
character, if they are also equal, then it will check the third, and so on till the first unmatched
character is found or the NULL character is found.
3. If a NULL character is found, the function returns zero as both strings will be the same.
4. If a non-matching character is found,
• If the ASCII value of the character of the first string is greater than that of the second
string, then the positive difference ( > 0) between their ASCII values is returned.
• If the ASCII value of the character of the first string is less than that of the second
string, then the negative difference ( < 0) between their ASCII values is returned.
Page 13 of 14
Group: BUET DU CSE MSc Admission Preparation Muhammad Aminul Islam
Master’s Admission Preparation Batch Lecture Note=4
THANK YOU
Page 14 of 14
Group: BUET DU CSE MSc Admission Preparation Muhammad Aminul Islam