0% found this document useful (0 votes)
4 views10 pages

C Programming: Pointers and Structures Guide

Uploaded by

Manjunath
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)
4 views10 pages

C Programming: Pointers and Structures Guide

Uploaded by

Manjunath
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

Introduction to C Programming N Manjunath Gowda

Department of Studies in Mechanical Engineering


University B.D.T. College of Engineering, Davanagere-577004
(A Constituent College of Visvesvaraya Technological University,
Belagavi-590018)

Introduction to C Programming
Module-05
1. Define a pointer. Summarize the arithmetic operations performed on pointers. (6 – marks)

Pointers are special variable which contain the memory address of any other variable (int, float, char,
etc...).
Pointer Arithmetic is the set of valid arithmetic operations that can be performed on pointers.
Operations that are allowed to perform on Pointers in C language are:

 Increment/Decrement of a Pointer
 Addition of integer to a pointer
 Subtraction of integer to a pointer
 Subtracting two pointers of the same type
 Comparison of pointers

Example:

#include <stdio.h>
int main()
{
int a = 22, b = 11, sum, dif;
int *p = &a, *q = &b;
printf("p = %d \n", p); // p = original address
printf("p = %d \n", q); // q = original address
p++;
printf("p++ = %d \n", p); //p++ = original address + 4
p--;
printf("p-- = %d \n", p); //p-- = previous address - 4
sum = p + 2; // sum = base address + 4*2
printf("%d\n",sum);
dif = q - 2; // dif = base address - 4*2
printf("%d",dif);
return 0 ;
}

Department of Mechanical Engineering, UBDTCE, Davangere


Introduction to C Programming N Manjunath Gowda

2. Develop a C program using pointer to compute the sum, mean and standard deviation of all
elements stored in any array of N real numbers. (08 – marks)

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

void main ()
{
float a[20], sum1 = 0, sum2 = 0, mean, var, dev;
int i, n;
printf ("Enter no of elements:");
scanf ("%d", &n);
printf ("Enter array elements:");
for (i = 0; i < n; i++)
{
scanf ("%f", a + i);
sum1 = sum1 + * (a + i);
}
mean = sum1 / n;
for (i = 0; i < n; i++)
{
sum2 = sum2 + pow ((*(a + i) - mean), 2);
}
var = sum2 / n;
dev = sqrt (var);
printf ("Sum :%f\n", sum1);
printf ("Mean :%f\n", mean);
printf ("Variance :%f\n", var);
printf ("Deviation :%f\n", dev);

Department of Mechanical Engineering, UBDTCE, Davangere


Introduction to C Programming N Manjunath Gowda

3. Differentiate between NULL pointer and Void pointer with examples. (6 – marks)

Ex: int *ptr = NULL; Ex: void *ptr;

4. Define a pointer. Explain with syntax pointer declaration and initialization with suitable
example. (6 – marks)

Pointers are special variable which contain the memory address of any other variable (int, float, char,
etc...).

Syntax

datatype * ptr_name;

Ex:

int x = 15;
int* pt; // pointer declaration
pt = &x; // pointer initialization

Example program:

#include<stdio.h>
int main()
{
int x = 15;

Department of Mechanical Engineering, UBDTCE, Davangere


Introduction to C Programming N Manjunath Gowda

int* pt;
pt = &x;
printf(“the value of x: %d \n”, x)
printf(“the address of x: %p \n”, &x)
printf(“the address of x: %p \n”, pt)
return 0;
}

5. Mention the rules for pointer operations (4 – marks)

A pointer variable can be assigned the address of another variable (of same data type).

A pointer variable can be assigned the value of another pointer variable (of same data type).

A pointer variable can be initialized with a NULL (or 0) value.

Prefix or postfix increment or decrement operators can be applied on a pointer variable.

An integer value can be added or subtracted from a pointer variable.

Two pointers can be subtracted.

A pointer variable can be compared with another pointer variable using relational operators.

A pointer variable cannot be multiplied by a constant.

A pointer variable cannot be added to another pointer variable.

6. How do you declare a pointer as an integer?

1. int &ptr;

2. int ptr;

3. int *ptr;

7. You have written a void swap() function to swap two numbers using Pointers.
Which of the following is the correct version?

1. void swap(int *ptr1, int *ptr2) {


int temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
}

Department of Mechanical Engineering, UBDTCE, Davangere


Introduction to C Programming N Manjunath Gowda

2. void swap(int *ptr1, int *ptr2) {


int temp = *ptr1;
*ptr1 = *ptr2;
*ptr1 = temp;
}
3. void swap(int *ptr1, int *ptr2) {
int temp = *ptr1;
*ptr2 = temp;
}

8. What is the output of the following code?

#include <stdio.h>

int main() {
int x = 10;
int *p = &x;
printf("%d\n", *p);
return 0;
}

1. 10
2. Garbage Value
3. Memory address of x
4. Error

9. What does the following code do?

int x = 10;
int *p = &x;
*p = *p + 5;
1. Adds 5 to the memory address stored in p
2. Adds 5 to the value stored in memory address stored in p
3. Changes the memory address stored in p
4. Multiplies the value stored at the memory address stored in p by 5

10. Prior to using a pointer variable it should be

a) Declared
b) Initialized
c) Both declared and initialized
d) None of these
Department of Mechanical Engineering, UBDTCE, Davangere
Introduction to C Programming N Manjunath Gowda

11. Is the NULL pointer same as an uninitialized pointer?

a) True
b) False

12. A pointer is a

a) variable that stores address of an instruction


b) variable that stores address of other variable
c) keyword used to create variables
d) None of these

13. What is a structure? Explain C syntax of structure declaration with an example. ( 6- marks)

Structures (also called structs) are a way to group several related variables into one place. Each
variable in the structure is known as a member of the structure.
Unlike an array, a structure can contain many different data types (int, float, char, etc.).

Name of
Keyword Structure

struct structureName
{
Members
dataType member1; of
dataType member2; Structure

};
Example:

#include<stdio.h>
struct student {
int R_No;
char *name;
} s1;
int main()
{
struct student s2;
s1.R_No = 001;
[Link] = "Manju";

Department of Mechanical Engineering, UBDTCE, Davangere


Introduction to C Programming N Manjunath Gowda

s2.R_No = 002;
[Link] = "Raju";
printf("%d \n",s1.R_No);
printf("%s \n",[Link]);
printf("%d \n",s2.R_No);
printf("%s \n",[Link]);
return 0; }

14. Explain with suitable examples, how the member of the structure are accessed, initialized
and declared in structure concept. (6 – marks)

Each variable in the structure is known as a member of the structure. In structure declaration, we
specify its member variables along with their datatype. We can use the struct keyword to declare the
structure in C using the following syntax:

Name of
Keyword Structure

struct structureName
{
Members
dataType member1; of
dataType member2; Structure

};
We can access structure members by using the ( . ) dot operator.

Example:

#include<stdio.h>
struct student {
int R_No;
char *name;
} s1;
int main()
{

Department of Mechanical Engineering, UBDTCE, Davangere


Introduction to C Programming N Manjunath Gowda

struct student s2;


s1.R_No = 001;
[Link] = "Manju";
s2.R_No = 002;
[Link] = "Raju";
printf("%d \n",s1.R_No);
printf("%s \n",[Link]);
printf("%d \n",s2.R_No);
printf("%s \n",[Link]);
return 0; }

15. What is the difference between array and structure? (3 – marks)

Parameter Structure in C Array in C


Definition A Structure is a data structure that An Array is a data structure that can only
can contain variables of different contain variables of the same data type.
data types.
Memory Structures do not require the data to Arrays store data in contiguous memory
Allocation be stored in consecutive memory locations, meaning that memory blocks are
locations. assigned consecutively.
Accessibility To access elements in a Structure, In Arrays, elements can be accessed by their
the name of the specific element is index.
required.
Pointer Structures do not use internal Arrays use internal Pointers that point to the
Pointers. first element in the array.
Instantiation An object can be created from a Arrays do not allow object creation after
Structure even after its declaration in their declaration.
the program.
Performance Structures can be slower to search Arrays can be faster to search and access due
and access due to the presence of to the absence of multiple data types.
multiple data types.

16. What is the size of a C structure?

a) C structure is always 128 bytes


b) Size of C structure is the totatl bytes of all elements of structure
c) Size of C structure is the size of largest elements
d) None of the above

Department of Mechanical Engineering, UBDTCE, Davangere


Introduction to C Programming N Manjunath Gowda

17. Choose a correct statement about C structure?


int main() {
struct ship {

};
return 0;
}

a) It is wrong to define an empty structure


b) Member variables can be added to a structure even after its first definition
c) There is no use of defining an empty structure
d) None of the above

18. Choose a correct statement about C structure elements?

a) Structure elements are stored on random free memory locations


b) structure elements are stored in register memory locations
c) structure elements are stored in contiguous memory locations
d) None of the above

19. What are the uses of C Structures?

a) structure is used to implement Linked Lists, Stack and Queue data structures
b) Structures are used in Operating System functionality like Display and Input taking
c) Structure are used to exchange information with peripherals of PC
d) All the above

20. Why structs in C?

Suppose you want to store information about a person: his/her name, citizenship number, and salary.
You can create different variables name, citNo and salary to store this information.
What if you need to store information of more than one person? Now, you need to create different
variables for each information per person: name1, citNo1, salary1, name2, citNo2, salary2, etc.
A better approach would be to have a collection of all related information under a single name Person
structure and use it for every person.

Department of Mechanical Engineering, UBDTCE, Davangere


Introduction to C Programming N Manjunath Gowda

15. Implement a structure to read, write and compute average marks of students, list of students
scoring above and below the average marks for a class of N students. ( 10 – marks)

#include<stdio.h>

struct student
{
char usn[10];
char name[10];
float m1,m2,m3;
float avg,total;
}s[20];

void main()
{
int n,i;
float sum=0.0;
printf("Enter the number of student=");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the detail of %d students\n",i+1);
printf("\n Enter USN=");
scanf("%s",s[i].usn);
printf("\n Enter Name=");
scanf("%s",s[i].name);
printf("Enter the three subject score\n");
scanf("%f%f%f",&s[i].m1,&s[i].m2,&s[i].m3);
s[i].total=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].total/3;
}
for(i=0;i<n;i++)
{
if(s[i].avg>=35)
printf("\n %s has scored above the average marks",s[i].name);
else
printf("\n %s has scored below the average marks",s[i].name);
}
}

Department of Mechanical Engineering, UBDTCE, Davangere

Common questions

Powered by AI

Before using a pointer variable effectively in C, it must first be declared with its data type, and then initialized with either a valid memory address or NULL. This ensures the pointer is ready for safe operations .

When a pointer is incremented, it increases by the size of the data type it points to. For example, an increment of an int pointer will add the size of an int (usually 4 bytes) to the pointer's current address. This characteristic is essential for navigating through arrays using pointers .

A NULL pointer in C is used in scenarios where a pointer needs to be initialized without pointing to a legitimate memory location to prevent undefined behavior, such as in function arguments to represent a non-specific target or as a sentinel value in data structures to signify the end. It enhances program robustness by avoiding dereferencing errors and is essential for indicating incomplete or unavailable data in code logic .

A NULL pointer is a pointer that is explicitly assigned a zero value, indicating it points to nothing and is often used for error handling in pointer-related functions, while a void pointer is a generic pointer type that can point to any data type but cannot be directly dereferenced without casting .

A structure can contain variables of different data types grouped together, while an array can only contain elements of the same data type. Structures do not require contiguous memory locations for the elements, unlike arrays, which do. Furthermore, structures cannot be accessed by index, but rather through named members, whereas arrays use indices .

Pointer arithmetic differs from regular arithmetic in that it involves operations like incrementing or decrementing pointers, adding or subtracting integers to/from pointers, and subtracting two pointers of the same type. These operations adjust the pointer by the size of the data type it points to .

A pointer in C programming is a special variable that contains the memory address of another variable, which can be of types such as int, float, char, etc. This allows for dynamic memory allocation and manipulation of data stored at the address it points to .

To compute the mean and standard deviation of an array using pointers, iterate through the array with a pointer to sum all elements, compute the mean by dividing by the element count, calculate variance by summing squared differences from the mean, and derive the standard deviation by taking the square root of the variance. This approach leverages pointer arithmetic for efficient element access and manipulation .

Rules for pointer operations include assigning a pointer the address of a variable of the same data type, copying the value of one pointer to another, initializing with NULL, incrementing or decrementing, adding or subtracting integers, subtracting two pointers of the same type, comparing pointers, and not multiplying or adding two pointers .

Structs are important for organizing complex data in C because they allow related variables of different data types to be grouped together logically under a single name. This facilitates the creation of composite data types and management of complex data, such as when storing multiple attributes for a person in a single variable rather than separately .

You might also like