0% found this document useful (0 votes)
9 views

Part 5, C Arrays & Pointers

Part 5, C Arrays & Pointers

Uploaded by

dimejihustle16
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Part 5, C Arrays & Pointers

Part 5, C Arrays & Pointers

Uploaded by

dimejihustle16
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

COURSE TITLE: COMPUTER PROGRAMMING I

COURSE CODE: CSC 203


NAME OF LECTURER: IBHARALU, F. I.
DEPARTMENT: COMPUTER SCIENCE

1
C ARRAYS
Array is a data structure in the C programming, which can store a fixed-size sequential
collection of elements of the same data type.
For example, if you want to store ten numbers, it is easier to define an array of 10 lengths,
instead of defining ten variables.

In the C programming language, an array can be One-Dimensional, Two-Dimensional, and


Multidimensional.

Table of Contents
# Define an Array in C
# Initialize an Array in C
# A Pictorial Representation of the Array:
# Accessing Array Elements in C

2
Define an Array in C
Syntax:
type arrayName [ size ];

This is called a one-dimensional array. An array type can be any valid C data types, and array
size must be an integer constant greater than zero.
Example:
double amount[5];

3
Initialize an Array in C

Arrays can be initialized at declaration time:


int age[5]={22, 25, 30, 32, 35};
OR
int age[]={22, 25, 30, 32, 35}; // the array size is optional when the
// initialization values are known and available

A Pictorial Representation of the Array:


Initializing each element separately in a loop:
int myArray[5];
int n = 0;

// Initializing elements of array seperately


for(n = 0; n < sizeof(myArray) / sizeof(myArray[0]); n++)
{
myArray[n] = n;
}

5
Accessing Array Elements in C
Example:

int myArray[5];
int n = 0;

// Initializing elements of array seperately


for(n=0;n<sizeof(myArray)/sizeof(myArray[0]);n++)
{
myArray[n] = n;
}

int a = myArray[3]; // Assigning 3rd element of array value to integer 'a'.

6
C Strings

In C programming, the one-dimensional array of characters are called strings, which is


terminated by a null character '\0’.

Table of Contents
# Strings Declaration in C
# Strings Initialization in C
# Memory Representation of Above Defined String in C
Strings Declaration in C

There are two ways to declare a string in C programming:


Example:

Through an array of characters.

char name[6];

Through pointers.

char *name; 7
Strings Initialization in C

Example:

char name[6] = {'C', 'l', 'o', 'u', 'd', '\0'};

or

char name[] = "Cloud";

Memory representation of above defined string in C is:

8
Example:

#include<stdio.h>

int main ()
{
char name[6] = {'C', 'l', 'o', 'u', 'd', '\0'};
printf("%s\n", name );
return 0;
}

Program Output: Cloud

9
C Pointers
A pointer is a variable in C, and the pointers value is the address of a memory location
in your RAM.

Table of Contents
# Pointer Definition in C
# Benefits of using Pointers in C
# How to Use Pointers in C

10
Pointer Definition in C
Syntax:
type *variable_name;

Example:
int *width;
char *letter;

Benefits of using Pointers in C:


Pointers allow the passing of arrays and strings to functions more efficiently.
Pointers make it possible to return more than one value from the function.
Pointers reduce the length and complexity of a program.
Pointers increase the processing speed.
Pointers save the memory.
11
How to Use Pointers in C
Example:

#include<stdio.h>

int main ()
{
int n = 20, *ptr; //actual and pointer variable declaration
ptr = &n; //store address of n in pointer variable
printf("Address of n variable: %x\n", &n );
printf("Address stored in ptr variable: %X\n", ptr ); //address stored in pointer variable
printf("Value of *ptr variable: %d\n", *ptr ); //access the value using the pointer
return 0;
}

Address of n variable: 2cb60f04


Address stored in ptr variable: 2CB60F04
Value of *ptr variable: 20

12
C Memory Management

C language provides many functions that come in header files to deal with the allocation and
management of memories. In this tutorial, you will find brief information about managing
memory in your program using some functions and their respective header files.

Table of Contents
# Management of Memory
# static memory allocations
# dynamic memory allocations
Management of Memory

Almost all computer languages can handle system memory. All the variables used in your
program occupies a precise memory space along with the program itself, which needs some
memory for storing itself (i.e., its own program). Therefore, in managing memory, utmost care
is one of the major tasks a programmer must keep in mind while writing codes.
13
When a variable gets assigned in a memory in one program, that memory location cannot be
used by another variable or another program. So, C language gives us a technique of allocating
memory to different variables and programs.

There are two types of memory allocations, they are:


static memory allocations
dynamic memory allocations
In the static memory allocation technique, allocation of memory is done at compilation time,
and it stays the same throughout the entire run of your program. No any changes will be in the
amount of memory or in the location of the memory.
In dynamic memory allocation technique, allocation of memory is done at the time of running
the program, and it also has the facility to increase/decrease the memory quantity allocated and
can also release or free the memory as and when not required or used. Reallocation of memory
can also be done when required. So, it is more advantageous, and memory can be managed
more efficiently.

14
C Dynamic Memory Allocation
malloc, calloc, or realloc are the three functions used to manipulate memory. These commonly
used functions are available through the stdlib library so you must include this library to use
them.

Table of Contents
# C - Dynamic memory allocation functions
# malloc function
# Example program for malloc() in C
# calloc function
# Example program for calloc() in C
# realloc function
# free function
# Example program for realloc() and free()

15
C - Dynamic memory allocation functions
Function Syntax
malloc() malloc (size); //memoryallocation
calloc() calloc (number_of_units, unit_size); //contiguous allocation
realloc() realloc (pointer_name, new_size); //re-allocation
free() free (pointer_name);

The malloc function


malloc function is used to allocate space in memory during the execution of the program.
malloc function does not initialize the memory allocated during execution. It carries
garbage value.
malloc function returns null pointer if it’s unable to allocate the requested amount of
memory.

16
Example program for malloc() in C

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void main()
{
char *allocated;
char *school = “Federal University of Agriculture, Abeokuta“;
int length = strlen(school);
allocated = (char *) malloc( length * sizeof(char) + 1 ); //memory allocated dynamically, +1 to accommodate the trailing ‘\0’

if(allocated == NULL )
{
printf("Couldn't allocate requested memory\n");
return;
}
else
{
strcpy(allocated, school);
}
printf("Dynamically allocated memory content: %s", allocated );
free(allocated);
}

Program Output:
Dynamically allocated memory content: Federal University of Agriculture, Abeokuta
17
calloc function

calloc() function and malloc () function are similar. But calloc() allocated memory is ascii zero-initialized. However, malloc() does not perform any
initialization.

Example:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void main()
{
char *school = “Federal University of Agriculture, Abeokuta“;
int size = strlen (school) + 1;
char *allocated = (char *) calloc(size, sizeof(char)); //memory allocated dynamically

if(allocated == NULL )
{
printf("Couldn't allocate requested memory\n");
return;
}
else
{
strcpy(allocated, school);
}
printf("Dynamically allocated memory content: %s", allocated);
free(allocated);
}

Program Output:

Dynamically allocated memory content: Federal University of Agriculture, Abeokuta

18
realloc function

realloc function modifies the allocated memory size by malloc and calloc functions to
new size.
If enough space doesn't exist in the memory of the current block to extend, a new block
is allocated for the full size of reallocation, then copies the existing data to the new block
and then frees the old block.

free function
free function frees the allocated memory by malloc (), calloc (), realloc () functions.

19
Example program for realloc() and free()

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void main()
{
char *school = “Federal University of Agriculture, Abeokuta“;
int size = strlen (school) + 1;
char *allocated = (char *) malloc(size, sizeof(char)); //memory allocated dynamically

if(allocated == NULL )
{
printf("Couldn't allocate requested memory\n");
return;
}
else
{
strcpy(allocated, school);
}

printf("Dynamically allocated memory content: "%s\n", allocated);

20
Contd: realloc() and free()

allocated = realloc(allocated, 100*sizeof(char));

if(allocated == NULL )
{
printf("Couldn't allocate requested memory\n");
return;
}
else
{
strcpy(allocated, "space is extended up to 100 characters");
}

printf("Resized memory: %s\n", allocated);


free(allocated);
}

Program Output:

Dynamically allocated memory content: Federal University of Agriculture, Abeokuta


Resized memory: space is extended up to 100 characters

Exercise:
Is a cast necessary for realloc()?
Why?

21
Thank you for your attention

22

You might also like