0% found this document useful (0 votes)
0 views16 pages

unit 4

The document provides an overview of various C programming concepts including dynamic memory allocation, structures, unions, pointers, and arrays. It includes example programs demonstrating these concepts, such as dynamic memory allocation for an array, nested structures, and passing structures to functions. Additionally, it covers the differences between structures and unions, and how to work with arrays of structures and pointers to structures.

Uploaded by

shanmukhgara48
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views16 pages

unit 4

The document provides an overview of various C programming concepts including dynamic memory allocation, structures, unions, pointers, and arrays. It includes example programs demonstrating these concepts, such as dynamic memory allocation for an array, nested structures, and passing structures to functions. Additionally, it covers the differences between structures and unions, and how to work with arrays of structures and pointers to structures.

Uploaded by

shanmukhgara48
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

1)Explain dynamic memory allocation with an example program.

The Dynamic memory allocation enables the C programmers to allocate memory at runtime.

The different functions that we used to allocate memory dynamically at run time are −

• malloc () − allocates a block of memory in bytes at runtime.


• calloc () − allocating continuous blocks of memory at run time.
• realloc () − used for reduce (or) extend the allocated memory.
• free () − deallocates previously allocated memory space.

Following C program is to display the elements and calculate sum of n numbers.

Using dynamic memory allocation functions, we are trying to reduce the wastage of memory.

#include <stdio.h>

#include <stdlib.h>

int main() {

int *dynamicArray;

int size;

// Get the size of the array from the user

printf("Enter the size of the array: ");

scanf("%d", &size);

// Allocate memory for the array dynamically

dynamicArray = (int *)malloc(size * sizeof(int));

// Check if memory allocation was successful

if (dynamicArray == NULL) {

printf("Memory allocation failed.\n");

return 1; // Exit the program with an error code


}

// Input values into the dynamically allocated array

printf("Enter %d integers:\n", size);

for (int i = 0; i < size; i++) {

scanf("%d", &dynamicArray[i]);

// Display the values in the dynamically allocated array

printf("You entered the following integers:\n");

for (int i = 0; i < size; i++) {

printf("%d ", dynamicArray[i]);

// Free the dynamically allocated memory

free(dynamicArray);

return 0;

2)Compare and contrast structures and unions.


3)Explain nested structures with suitable examples.

A nested structure in C is a structure within structure. One structure can be declared inside another
structure in the same way structure members are declared inside a structure.

Syntax:

struct name_1
{
member1;
member2;
.
.
membern;

struct name_2
{
member_1;
member_2;
.
.
member_n;
}, var1
} var2;

program-
#include <stdio.h>
#include <string.h>

struct Organisation
{
char organisation_name[20];
char org_number[20];

struct Employee
{
int employee_id;
char name[20];
int salary;
} emp;
};

int main()
{
struct Organisation org;

printf("The size of structure organisation : %ld\n",


sizeof(org));

org.emp.employee_id = 101;
strcpy(org.emp.name, "Robert");
org.emp.salary = 400000;
strcpy(org.organisation_name,
"GeeksforGeeks");
strcpy(org.org_number, "GFG123768");

// Printing the details


printf("Organisation Name : %s\n",
org.organisation_name);
printf("Organisation Number : %s\n",
org.org_number);
printf("Employee id : %d\n",
org.emp.employee_id);
printf("Employee name : %s\n",
org.emp.name);
printf("Employee Salary : %d\n",
org.emp.salary);
}

Output:

The size of structure organisation : 68


Organisation Name : GeeksforGeeks
Organisation Number : GFG123768
Employee id : 101
Employee name : Robert
Employee Salary : 400000

4)Define pointer and explain how the pointer variable is declared and initialized in C.

A pointer is defined as a derived data type that can store the address of other C variables or a
memory location. We can access and manipulate the data stored in that memory location using
pointers.

Syntax of C Pointers

The syntax of pointers is similar to the variable declaration in C, but we use the ( * )
dereferencing operator in the pointer declaration.

datatype * ptr;

where

• ptr is the name of the pointer.

• datatype is the type of data it is pointing to.

The use of pointers in C can be divided into three steps:

1. Pointer Declaration

2. Pointer Initialization

3. Pointer Dereferencing
1. Pointer Declaration

In pointer declaration, we only declare the pointer but do not initialize it. To declare a
pointer, we use the

( * ) dereference operator before its name.

int *ptr;
2. Pointer Initialization

Pointer initialization is the process where we assign some initial value to the pointer variable.
We generally use the ( & ) addressof operator to get the memory address of a variable and
then store it in the pointer variable.

Example

int var = 10;


int * ptr;
ptr = &var;

program-

// C program to illustrate Pointers


#include <stdio.h>

void geeks()
{
int var = 10;

// declare pointer variable


int* ptr;

// note that data type of ptr and var must be same


ptr = &var;

// assign the address of a variable to a pointer


printf("Value at ptr = %p \n", ptr);
printf("Value at var = %d \n", var);
printf("Value at *ptr = %d \n", *ptr);
}

// Driver program
int main()
{
geeks();
return 0;
}

5)Explain pointers with arrays with an example program.

Syntax:

pointer_type *array_name [array_size];


// C program to demonstrate the use of array of pointers
#include <stdio.h>

int main()
{
// declaring some temp variables
int var1 = 10;
int var2 = 20;
int var3 = 30;

// array of pointers to integers


int* ptr_arr[3] = { &var1, &var2, &var3 };

// traversing using loop


for (int i = 0; i < 3; i++) {
printf("Value of var%d: %d\tAddress: %p\n", i + 1, *ptr_arr[i],
ptr_arr[i]);
}

return 0;
}

6)Explain array of structures with an example program.

struct tagname{
datatype member1;
datatype member2;
datatype member n;
};

#include<stdio.h>

struct student

char name[20];

int id;

float marks;

};

void main()

struct student s1,s2,s3;

int dummy;

printf("Enter the name, id, and marks of student 1 ");


scanf("%s %d %f",s1.name,&s1.id,&s1.marks);

scanf("%c",&dummy);

printf("Enter the name, id, and marks of student 2 ");

scanf("%s %d %f",s2.name,&s2.id,&s2.marks);

scanf("%c",&dummy);

printf("Enter the name, id, and marks of student 3 ");

scanf("%s %d %f",s3.name,&s3.id,&s3.marks);

scanf("%c",&dummy);

printf("Printing the details....\n");

printf("%s %d %f\n",s1.name,s1.id,s1.marks);

printf("%s %d %f\n",s2.name,s2.id,s2.marks);

printf("%s %d %f\n",s3.name,s3.id,s3.marks);

Output

Enter the name, id, and marks of student 1 James 90 90


Enter the name, id, and marks of student 2 Adoms 90 90
Enter the name, id, and marks of student 3 Nick 90 90
Printing the details....
James 90 90.000000
Adoms 90 90.000000
Nick 90 90.000000

7) Write a C program to illustatre union.


#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <stdlib.h>

union student
{
int id;
char name[20];
};

int main(int argc, char **argv)


{
union student st[10];
int n, i;
printf("Enter a number between 1 to 10: ");
scanf("%d", &n);
for(i = 1; i <= n; i++)
{
printf("\nEnter details of student %d:", i);
printf("\nId of student %d: ", i);
scanf("%d", &st[i].id);
printf("\nStudent %d Id: %d", i, st[i].id);
printf("\nName of student %d: ", i);
fflush(stdin);
gets(st[i].name);
printf("\nStudent %d Name: ", i);
puts(st[i].name);
}
getch();
return 0;
}
Output:
Enter a number between 1 to 10: 2

Enter details of student 1:


Id of student 1: 101

Student 1 Id: 101


Name of student 1: teja

Student 1 Name: teja

Enter details of student 2:


Id of student 2: 102

Student 2 Id: 102


Name of student 2: sruthi

Student 2 Name: Sruthi

8)C program to print city names using array of pointers.

#include <stdio.h>

int main() {
// Array of pointers to strings (city names)
const char *cities[] = {
"New York",
"London",
"Tokyo",
"Paris",
"Sydney"
};

// Calculate the number of cities


int numCities = sizeof(cities) / sizeof(cities[0]);

// Display the city names using a loop


printf("List of Cities:\n");
for (int i = 0; i < numCities; i++) {
printf("%d. %s\n", i + 1, cities[i]);
}

return 0;
}
Output –
List of Cities:
1. New York
2. London
3. Tokyo
4. Paris
5. Sydney

9)C program to illustrate pointer to structure.

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

// Define a structure to represent a person


struct Person {
char name[50];
int age;
float height;
};

int main() {
// Declare a structure variable
struct Person person1;

// Initialize the structure using dot notation


strcpy(person1.name, "John Doe");
person1.age = 25;
person1.height = 5.9;

// Declare a pointer to the structure


struct Person *ptrPerson;

// Assign the address of the structure variable to the pointer


ptrPerson = &person1;

// Access structure members using arrow notation through the pointer


printf("Person Information:\n");
printf("Name: %s\n", ptrPerson->name);
printf("Age: %d\n", ptrPerson->age);
printf("Height: %.2f feet\n", ptrPerson->height);

return 0;
}

Output-
Person Information:
Name: John Doe
Age: 25
Height: 5.90 feet

10)what are the different ways to pass a structure to functions?

Pass by Value: In this method, a copy of the entire structure is passed to the function.

c
• #include <stdio.h>
struct Point {
int x;
int y;
};

void displayPoint(struct Point p) {


printf("Point: (%d, %d)\n", p.x, p.y);
}

int main() {
struct Point myPoint = {5, 10};
displayPoint(myPoint);

return 0;
}

The downside of passing by value is that it involves copying the entire structure, which can
be inefficient for large structures.

• Pass by Address (Using Pointers): In this method, a pointer to the structure is passed to
the function. This allows the function to directly modify the original structure.

c
• #include <stdio.h>

struct Point {
int x;
int y;
};

void displayPoint(struct Point *p) {


printf("Point: (%d, %d)\n", p->x, p->y);
}

int main() {
struct Point myPoint = {5, 10};
displayPoint(&myPoint);

return 0;
}

Passing by address is more efficient than passing by value for large structures, and it allows
the function to modify the original structure.

• Pass by Reference (Using Pointers): Although C does not have true pass by reference,
you can simulate it by passing a pointer to the structure. This way, modifications made inside
the function affect the original structure.

c
#include <stdio.h>

struct Point {
int x;
int y;
};

void displayPoint(struct Point *p) {


printf("Point: (%d, %d)\n", p->x, p->y);
// Modify the structure
p->x = 20;
p->y = 30;
}

int main() {
struct Point myPoint = {5, 10};
displayPoint(&myPoint);

// After the function call, myPoint's values are modified


printf("Modified Point: (%d, %d)\n", myPoint.x, myPoint.y);

return 0;
}

11)Write a C program to calculate the student total marks, subject’s total marks and total marks
using array of structures.

#include <stdio.h>

// Define the structure for a subject

struct Subject {

char name[50];

int marks;

};

// Define the structure for a student

struct Student {

char name[50];

struct Subject subjects[3]; // Assuming there are 3 subjects

int totalMarks; // Total marks for the student

};

int main() {

const int numStudents = 3; // Number of students

const int numSubjects = 3; // Number of subjects

// Declare an array of structures for students

struct Student students[numStudents];


// Input data for each student and subject

for (int i = 0; i < numStudents; i++) {

printf("Enter details for student %d:\n", i + 1);

printf("Name: ");

scanf("%s", students[i].name);

for (int j = 0; j < numSubjects; j++) {

printf("Enter marks for subject %d: ", j + 1);

scanf("%d", &students[i].subjects[j].marks);

// Calculate total marks for each student and each subject

for (int i = 0; i < numStudents; i++) {

students[i].totalMarks = 0;

for (int j = 0; j < numSubjects; j++) {

students[i].totalMarks += students[i].subjects[j].marks;

// Calculate total marks for each subject

int subjectTotal[numSubjects] = {0};

for (int i = 0; i < numStudents; i++) {

for (int j = 0; j < numSubjects; j++) {

subjectTotal[j] += students[i].subjects[j].marks;

// Calculate overall total marks


int overallTotal = 0;

for (int i = 0; i < numStudents; i++) {

overallTotal += students[i].totalMarks;

// Display the results

printf("\nStudent-wise Total Marks:\n");

for (int i = 0; i < numStudents; i++) {

printf("%s: %d\n", students[i].name, students[i].totalMarks);

printf("\nSubject-wise Total Marks:\n");

for (int j = 0; j < numSubjects; j++) {

printf("Subject %d: %d\n", j + 1, subjectTotal[j]);

printf("\nOverall Total Marks: %d\n", overallTotal);

return 0;

12) Write a C program to pass a student structure to function and display structure members in the
function.

#include <stdio.h>

// Define the structure for a student

struct Student {

char name[50];

int rollNumber;

float marks;

};
// Function to display student information

void displayStudent(struct Student student) {

printf("Student Information:\n");

printf("Name: %s\n", student.name);

printf("Roll Number: %d\n", student.rollNumber);

printf("Marks: %.2f\n", student.marks);

int main() {

// Declare and initialize a student structure

struct Student myStudent = {"John Doe", 101, 85.5};

// Call the function to display student information

displayStudent(myStudent);

return 0;

Output-

Student Information:

Name: John Doe

Roll Number: 101

Marks: 85.50

You might also like