Sie sind auf Seite 1von 28

PPS : UNIT-IV

Pointers Structures and Unions in C Language:


By B. Ramadasu CSE,CBIT
A pointer is a variable that stores the address of another variable. Unlike other variables that
hold values of a certain type, pointer holds the address of a variable. For example, an integer
variable holds (or you can say stores) an integer value, however an integer pointer holds the
address of a integer variable. In this guide, we will discuss pointers in C programming with the
help of examples.

Before we discuss about pointers in C, lets take a simple example to understand what do we
mean by the address of a variable.

A simple example to understand how to access the address of a variable without pointers?

In this program, we have a variable num of int type. The value of num is 10 and this value must
be stored somewhere in the memory, right? A memory space is allocated for each variable that
holds the value of that variable, this memory space has an address. For example we live in a
house and our house has an address, which helps other people to find our house. The same way
the value of the variable is stored in a memory address, which helps the C program to find that
value when it is needed.

So let‟s say the address assigned to variable num is 0x7fff5694dc58, which means whatever
value we would be assigning to num should be stored at the location: 0x7fff5694dc58. See the
diagram below.

#include <stdio.h>
int main()
{
int num = 10;
printf("Value of variable num is: %d", num);
/* To print the address of a variable we use %p
* format specifier and ampersand (&) sign just
* before the variable name like &num.
*/
printf("\nAddress of variable num is: %p", &num);
return 0;
}

Output:

Value of variable num is: 10


Address of variable num is: 0x7fff5694dc58
A Simple Example of Pointers in C

This program shows how a pointer is declared and used. There are several other things that we
can do with pointers, we have discussed them later in this guide. For now, we just need to know
how to link a pointer to the address of a variable.

Important point to note is: The data type of pointer and the variable must match, an int pointer
can hold the address of int variable, similarly a pointer declared with float data type can hold the
address of a float variable. In the example below, the pointer and the variable both are of int
type.

#include <stdio.h>
int main()
{
//Variable declaration
int num = 10;

//Pointer declaration
int *p;

//Assigning address of num to the pointer p


p = #

printf("Address of variable num is: %p", p);


return 0;
}

Output:

Address of variable num is: 0x7fff5694dc58

C Pointers – Operators that are used with Pointers

Lets discuss the operators & and * that are used with Pointers in C.

“Address of”(&) Operator

We have already seen in the first example that we can display the address of a variable using
ampersand sign. I have used &num to access the address of variable num. The & operator is
also known as “Address of” Operator.
printf("Address of var is: %p", &num);

Point to note: %p is a format specifier which is used for displaying the address in hex format.
Now that you know how to get the address of a variable but how to store that address in some
other variable? That‟s where pointers comes into picture. As mentioned in the beginning of this
guide, pointers in C programming are used for holding the address of another variables.

Pointer is just like another variable, the main difference is that it stores address of another
variable rather than a value.

“Value at Address”(*) Operator

The * Operator is also known as Value at address operator.

How to declare a pointer?

int *p1 /*Pointer to an integer variable*/


double *p2 /*Pointer to a variable of data type double*/
char *p3 /*Pointer to a character variable*/
float *p4 /*pointer to a float variable*/

The above are the few examples of pointer declarations. If you need a pointer to store the
address of integer variable then the data type of the pointer should be int. Same case is with
the other data types.

By using * operator we can access the value of a variable through a pointer.


For example:

double a = 10;
double *p;
p = &a;

*p would give us the value of the variable a. The following statement would display 10 as
output.

printf("%d", *p);

Similarly if we assign a value to *pointer like this:

*p = 200;

It would change the value of variable a. The statement above will change the value of a from 10
to 200.

Example of Pointer demonstrating the use of & and *


#include <stdio.h>
int main()
{
/* Pointer of integer type, this can hold the
* address of a integer type variable.
*/
int *p;

int var = 10;

/* Assigning the address of variable var to the pointer


* p. The p can hold the address of var because var is
* an integer type variable.
*/
p= &var;

printf("Value of variable var is: %d", var);


printf("\nValue of variable var is: %d", *p);
printf("\nAddress of variable var is: %p", &var);
printf("\nAddress of variable var is: %p", p);
printf("\nAddress of pointer p is: %p", &p);
return 0;
}

Output:

Value of variable var is: 10


Value of variable var is: 10
Address of variable var is: 0x7fff5ed98c4c
Address of variable var is: 0x7fff5ed98c4c
Address of pointer p is: 0x7fff5ed98c50

Lets take few more examples to understand it better –


Lets say we have a char variable ch and a pointer ptr that holds the address of ch.

char ch='a';
char *ptr;
Read the value of ch

printf("Value of ch: %c", ch);


or
printf("Value of ch: %c", *ptr);

Change the value of ch

ch = 'b';
or
*ptr = 'b';

The above code would replace the value „a‟ with „b‟.

Can you guess the output of following C program?

#include <stdio.h>
int main()
{
int var =10;
int *p;
p= &var;

printf ( "Address of var is: %p", &var);


printf ( "\nAddress of var is: %p", p);

printf ( "\nValue of var is: %d", var);


printf ( "\nValue of var is: %d", *p);
printf ( "\nValue of var is: %d", *( &var));

/* Note I have used %p for p's value as it represents an address*/


printf( "\nValue of pointer p is: %p", p);
printf ( "\nAddress of pointer p is: %p", &p);

return 0;
}

Output:

Address of var is: 0x7fff5d027c58


Address of var is: 0x7fff5d027c58
Value of var is: 10
Value of var is: 10
Value of var is: 10
Value of pointer p is: 0x7fff5d027c58
Address of pointer p is: 0x7fff5d027c50

More Topics on Pointers

1) Pointer to Pointer – A pointer can point to another pointer (which means it can store the
address of another pointer), such pointers are known as double pointer OR pointer to pointer.
2) Passing pointers to function – Pointers can also be passed as an argument to a function,
using this feature a function can be called by reference as well as an array can be passed to a
function while calling.

3) Function pointers – A function pointer is just like another pointer, it is used for storing the
address of a function. Function pointer can also be used for calling a function in C program.

We already know that a pointer holds the address of another variable of same type. When a
pointer holds the address of another pointer then such type of pointer is known as pointer-to-
pointer or double pointer. In this guide, we will learn what is a double pointer, how to declare
them and how to use them in C programming. To understand this concept, you should know the
basics of pointers.

How to declare a Pointer to Pointer (Double Pointer) in C?


int **pr;

Here pr is a double pointer. There must be two *‟s in the declaration of double pointer.

Let‟s understand the concept of double pointers with the help of a diagram:

As per the diagram, pr2 is a normal pointer that holds the address of an integer variable num.
There is another pointer pr1 in the diagram that holds the address of another pointer pr2, the
pointer pr1 here is a pointer-to-pointer (or double pointer).

Values from above diagram:

Variable num has address: XX771230


Address of Pointer pr1 is: XX661111
Address of Pointer pr2 is: 66X123X1
Example of double Pointer

Lets write a C program based on the diagram that we have seen above.

#include <stdio.h>
int main()
{
int num=123;

//A normal pointer pr2


int *pr2;

//This pointer pr2 is a double pointer


int **pr1;

/* Assigning the address of variable num to the


* pointer pr2
*/
pr2 = #

/* Assigning the address of pointer pr2 to the


* pointer-to-pointer pr1
*/
pr1 = &pr2;

/* Possible ways to find value of variable num*/


printf("\n Value of num is: %d", num);
printf("\n Value of num using pr2 is: %d", *pr2);
printf("\n Value of num using pr1 is: %d", **pr1);

/*Possible ways to find address of num*/


printf("\n Address of num is: %p", &num);
printf("\n Address of num using pr2 is: %p", pr2);
printf("\n Address of num using pr1 is: %p", *pr1);

/*Find value of pointer*/


printf("\n Value of Pointer pr2 is: %p", pr2);
printf("\n Value of Pointer pr2 using pr1 is: %p", *pr1);

/*Ways to find address of pointer*/


printf("\n Address of Pointer pr2 is:%p",&pr2);
printf("\n Address of Pointer pr2 using pr1 is:%p",pr1);

/*Double pointer value and address*/


printf("\n Value of Pointer pr1 is:%p",pr1);
printf("\n Address of Pointer pr1 is:%p",&pr1);

return 0;
}

Output:

Value of num is: 123


Value of num using pr2 is: 123
Value of num using pr1 is: 123
Address of num is: XX771230
Address of num using pr2 is: XX771230
Address of num using pr1 is: XX771230
Value of Pointer pr2 is: XX771230
Value of Pointer pr2 using pr1 is: XX771230
Address of Pointer pr2 is: 66X123X1
Address of Pointer pr2 using pr1 is: 66X123X1
Value of Pointer pr1 is: 66X123X1
Address of Pointer pr1 is: XX661111

There are some confusions regarding the output of this program, when you run this program you
would see the address similar to this: 0x7fff54da7c58. The reason I have given the address in
different format is because I want you to relate this program with the diagram above. I have used
the exact address values in the above diagram so that it would be easy for you to relate the output
of this program with the above diagram.

You can also understand the program logic with these simple equations:

num == *pr2 == **pr1


&num == pr2 == *pr1
&pr2 == pr1

Passing pointer to a function in C with example

In this tutorial, you will learn how to pass a pointer to a function as an argument. To understand
this concept you must have a basic idea of Pointers and functions in C programming.

Just like any other argument, pointers can also be passed to a function as an argument. Lets take
an example to understand how this is done.

Example: Passing Pointer to a Function in C Programming

In this example, we are passing a pointer to a function. When we pass a pointer as an argument
instead of a variable then the address of the variable is passed instead of the value. So any
change made by the function using the pointer is permanently made at the address of passed
variable. This technique is known as call by reference in C.

Try this same program without pointer, you would find that the bonus amount will not reflect in
the salary, this is because the change made by the function would be done to the local variables
of the function. When we use pointers, the value is changed at the address of variable

#include <stdio.h>
void salaryhike(int *var, int b)
{
*var = *var+b;
}
int main()
{
int salary=0, bonus=0;
printf("Enter the employee current salary:");
scanf("%d", &salary);
printf("Enter bonus:");
scanf("%d", &bonus);
salaryhike(&salary, bonus);
printf("Final salary: %d", salary);
return 0;
}

Output:

Enter the employee current salary:10000


Enter bonus:2000
Final salary: 12000

Example 2: Swapping two numbers using Pointers

This is one of the most popular example that shows how to swap numbers using call by
reference.

Try this program without pointers, you would see that the numbers are not swapped. The reason
is same that we have seen above in the first example.

#include <stdio.h>
void swapnum(int *num1, int *num2)
{
int tempnum;

tempnum = *num1;
*num1 = *num2;
*num2 = tempnum;
}
int main( )
{
int v1 = 11, v2 = 77 ;
printf("Before swapping:");
printf("\nValue of v1 is: %d", v1);
printf("\nValue of v2 is: %d", v2);

/*calling swap function*/


swapnum( &v1, &v2 );

printf("\nAfter swapping:");
printf("\nValue of v1 is: %d", v1);
printf("\nValue of v2 is: %d", v2);
}

Output:

Before swapping:
Value of v1 is: 11
Value of v2 is: 77
After swapping:
Value of v1 is: 77
Value of v2 is: 11

C – Function Pointer with examples

In C programming language, we can have a concept of Pointer to a function known as function


pointer in C. In this tutorial, we will learn how to declare a function pointer and how to call a
function using this pointer. To understand this concept, you should have the basic knowledge of
Functions and Pointers in C.

How to declare a function pointer?


function_return_type(*Pointer_name)(function argument list)

For example:

double (*p2f)(double, char)

Here double is a return type of function, p2f is name of the function pointer and (double, char) is
an argument list of this function. Which means the first argument of this function is of double
type and the second argument is char type.

Lets understand this with the help of an example: Here we have a function sum that calculates the
sum of two numbers and returns the sum. We have created a pointer f2p that points to this
function, we are invoking the function using this function pointer f2p.

int sum (int num1, int num2)


{
return num1+num2;
}
int main()
{

/* The following two lines can also be written in a single


* statement like this: void (*fun_ptr)(int) = &fun;
*/
int (*f2p) (int, int);
f2p = sum;
//Calling function using function pointer
int op1 = f2p(10, 13);

//Calling function in normal way using function name


int op2 = sum(10, 13);

printf("Output1: Call using function pointer: %d",op1);


printf("\nOutput2: Call using function name: %d", op2);

return 0;
}

Output:
Output1: Call using function pointer: 23
Output2: Call using function name: 23

Some points regarding function pointer:


1. As mentioned in the comments, you can declare a function pointer and assign a function to it
in a single statement like this:

void (*fun_ptr)(int) = &fun;

2. You can even remove the ampersand from this statement because a function name alone
represents the function address. This means the above statement can also be written like this:

void (*fun_ptr)(int) = fun;

Pointer and Array in C programming with example

In this guide, we will learn how to work with Pointers and arrays in a C program. I recommend
you to refer Array and Pointer tutorials before going though this guide so that it would be easy
for you to understand the concept explained here.

A simple example to print the address of array elements


#include <stdio.h>
int main( )
{
int val[7] = { 11, 22, 33, 44, 55, 66, 77 } ;
/* for loop to print value and address of each element of array*/
for ( int i = 0 ; i < 7 ; i++ )
{
/* The correct way of displaying the address would be using %p format
* specifier like this:
* printf("val[%d]: value is %d and address is %p\n", i, val[i],
&val[i]);
* Just to demonstrate that the array elements are stored in contiguous
* locations, I m displaying the addresses in integer
*/
printf("val[%d]: value is %d and address is %d\n", i, val[i], &val[i]);
}
return 0;
}

Output:

val[0]: value is 11 and address is 1423453232


val[1]: value is 22 and address is 1423453236
val[2]: value is 33 and address is 1423453240
val[3]: value is 44 and address is 1423453244
val[4]: value is 55 and address is 1423453248
val[5]: value is 66 and address is 1423453252
val[6]: value is 77 and address is 1423453256
Note that there is a difference of 4 bytes between each element because that‟s the size of an
integer. Which means all the elements are stored in consecutive contiguous memory locations in
the memory.(See the diagram below)

In the above example I have used &val[i] to get the address of ith element of the array. We can
also use a pointer variable instead of using the ampersand (&) to get the address.

Example – Array and Pointer Example in C


#include <stdio.h>
int main( )
{
/*Pointer variable*/
int *p;

/*Array declaration*/
int val[7] = { 11, 22, 33, 44, 55, 66, 77 } ;

/* Assigning the address of val[0] the pointer


* You can also write like this:
* p = var;
* because array name represents the address of the first element
*/
p = &val[0];

for ( int i = 0 ; i<7 ; i++ )


{
printf("val[%d]: value is %d and address is %p\n", i, *p, p);
/* Incrementing the pointer so that it points to next element
* on every increment.
*/
p++;
}
return 0;
}
Output:

val[0]: value is 11 and address is 0x7fff51472c30


val[1]: value is 22 and address is 0x7fff51472c34
val[2]: value is 33 and address is 0x7fff51472c38
val[3]: value is 44 and address is 0x7fff51472c3c
val[4]: value is 55 and address is 0x7fff51472c40
val[5]: value is 66 and address is 0x7fff51472c44
val[6]: value is 77 and address is 0x7fff51472c48

Points to Note:
1) While using pointers with array, the data type of the pointer must match with the data type of
the array.
2) You can also use array name to initialize the pointer like this:

p = var;

because the array name alone is equivalent to the base address of the array.

val==&val[0];

3) In the loop the increment operation(p++) is performed on the pointer variable to get the next
location (next element‟s location), this arithmetic is same for all types of arrays (for all data
types double, char, int etc.) even though the bytes consumed by each data type is different.

Pointer logic
You must have understood the logic in above code so now its time to play with few pointer
arithmetic and expressions.

if p = &val[0] which means


*p ==val[0]
(p+1) == &val[2] & *(p+1) == val[2]
(p+2) == &val[3] & *(p+2) == val[3]
(p+n) == &val[n+1) & *(p+n) == val[n+1]

Using this logic we can rewrite our code in a better way like this:

#include <stdio.h>
int main( )
{
int *p;
int val[7] = { 11, 22, 33, 44, 55, 66, 77 } ;
p = val;
for ( int i = 0 ; i<7 ; i++ )
{
printf("val[%d]: value is %d and address is %p\n", i, *(p+i), (p+i));
}
return 0;
}

We don‟t need the p++ statement in this program.


Structures and Unions :

Structures :
A structure is a user-defined data type available in C that allows to combining data items of
different kinds. Structures are used to represent a record.
Defining a structure: To define a structure, you must use the struct statement. The struct
statement defines a new data type, with more than or equal to one member. The format of the
struct statement is as follows:

struct [structure name]


{
member definition;
member definition;
...
member definition;
};

Unions :
A union is a special data type available in C that allows storing different data types in the same
memory location. You can define a union with many members, but only one member can contain
a value at any given time. Unions provide an efficient way of using the same memory location
for multiple purposes.
Defining a Union: To define a union, you must use the union statement in the same way as you
did while defining a structure. The union statement defines a new data type with more than one
member for your program. The format of the union statement is as follows:

union [union name]


{
member definition;
member definition;
...
member definition;
};

Similarities between Structure and Union

1. Both are user-defined data types used to store data of different types as a single unit.
2. Their members can be objects of any type, including other structures and unions or
arrays. A member can also consist of a bit field.
3. Both structures and unions support only assignment = and sizeof operators. The two
structures or unions in the assignment must have the same members and member types.
4. A structure or a union can be passed by value to functions and returned by value by
functions. The argument must have the same type as the function parameter. A structure
or union is passed by value just like a scalar variable as a corresponding parameter.
5. ‘.’ operator is used for accessing members.

Differences

// C program to illustrate differences


// between structure and Union
#include <stdio.h>
#include <string.h>

// declaring structure
struct struct_example
{
int integer;
float decimal;
char name[20];
};

// declaraing union

union union_example
{
int integer;
float decimal;
char name[20];
};

void main()
{
// creating variable for structure
// and initializing values difference
// six
struct struct_example s={18,38,"geeksforgeeks"};

// creating variable for union


// and initializing values
union union_example u={18,38,"geeksforgeeks"};

printf("structure data:\n integer: %d\n"


"decimal: %.2f\n name: %s\n",
s.integer, s.decimal, s.name);
printf("\nunion data:\n integeer: %d\n"
"decimal: %.2f\n name: %s\n",
u.integer, u.decimal, u.name);

// difference two and three


printf("\nsizeof structure : %d\n", sizeof(s));
printf("sizeof union : %d\n", sizeof(u));

// difference five
printf("\n Accessing all members at a time:");
s.integer = 183;
s.decimal = 90;
strcpy(s.name, "geeksforgeeks");

printf("structure data:\n integer: %d\n "


"decimal: %.2f\n name: %s\n",
s.integer, s.decimal, s.name);

u.integer = 183;
u.decimal = 90;
strcpy(u.name, "geeksforgeeks");

printf("\nunion data:\n integeer: %d\n "


"decimal: %.2f\n name: %s\n",
u.integer, u.decimal, u.name);

printf("\n Accessing one member at time:");

printf("\nstructure data:");
s.integer = 240;
printf("\ninteger: %d", s.integer);

s.decimal = 120;
printf("\ndecimal: %f", s.decimal);

strcpy(s.name, "C programming");


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

printf("\n union data:");


u.integer = 240;
printf("\ninteger: %d", u.integer);

u.decimal = 120;
printf("\ndecimal: %f", u.decimal);

strcpy(u.name, "C programming");


printf("\nname: %s\n", u.name);

//difference four
printf("\nAltering a member value:\n");
s.integer = 1218;
printf("structure data:\n integer: %d\n "
" decimal: %.2f\n name: %s\n",
s.integer, s.decimal, s.name);

u.integer = 1218;
printf("union data:\n integer: %d\n"
" decimal: %.2f\n name: %s\n",
u.integer, u.decimal, u.name);
}

Output:

structure data:
integer: 18
decimal: 38.00
name: geeksforgeeks

union data:
integeer: 18
decimal: 0.00
name: ?

sizeof structure: 28
sizeof union: 20

Accessing all members at a time: structure data:


integer: 183
decimal: 90.00
name: geeksforgeeks

union data:
integeer: 1801807207
decimal: 277322871721159510000000000.00
Accessing one member at a time:
structure data:
integer: 240
decimal: 120.000000
name: C programming

union data:
integer: 240
decimal: 120.000000
name: C programming
Altering a member value:
structure data:
integer: 1218
decimal: 120.00
name: C programming
union data:
integer: 1218
decimal: 0.00
name: ?

Enumerated data type

Enumerated data type is a user defined data type. It grabs integer vales from a list. Integer values
are actually replaced by alphabetic or descriptive names. It increases ease of read of the program.
These detailed names are known as enumerators or enumerator constants. Together they form a
list which is apparently called enumerator list. Format of enumerated data type is as shown
below:

enum tag_of_name

member_1

member_2

...

};

Figure Format of enumerated data type

Explanation: Here,

enum is the keyword

tag_of_name is the identifier/user given name which represents enumerated data type

enum tag_of_name represents derived data type when combined together

member_1, member_2,... represents constants of type integer. These integer constants


are represented by their detailed names. These are known as enumerators.
Member_1, member_2 are not variables. They are constants. Compiler itself assigns value 0 to
first member or member_1, value 1 to member_2 and subsequent members will be assigned the
values in increasing order sequentially.

Let us consider an example of enumerated data type so that it can be better understood:

enum employee_depart

it, operations, management, accounts, stores

};

Explanation: Here,

enum is the keyword

employee_depart is the name of tag or name of enumerated data type

it, operations, management, accounts, stores are enumerators

Compiler will assign vale 1 to it, operations will be assigned value 2 and so on.

Since we know the syntax of defining enumerated data type next step is to declare variables for
this data type. Syntax is as shown below:

enum tag_of_name variables;

Let us consider the above example of enumerators and using that the variables will be declared
as :

enum employee_depart emp, em;

Explanation: Here,

enum employee_depart is the derived data type

emp, em are the variables of enumerated data type

We can explicitly assign values to these enumerators also. Let us consider an example:
enum months
{
january, february, march, april, may, june, july, august, september, october, november,
december
};
enum months month1, month2

Explanation: Here,

enum months is the derived data type

january, february, march,..., december will assigned values from 0, 1, 2, …, 11


respectively.

month1, month2 are the variables of enumerated data type

We can assign values to these members. Let us consider the example

enum months
{
january=4, february, march, april=0, may, june, july
}month1;

Explanation: Here,

january=4 will assign value 4 to january then february will be assigned value 5 followed
by march with value 6. Now april is assigned value 0 then may will be assigned 1
followed by june with value 2 and then july to value 3 respectively.

Let us consider a program to illustrate the enumerated data type.

/* Program to illustrate enumerated data type*/

# include <stdio.h>

# include <conio.h>

# include <string.h>

# include <stdlib.h>
void main()

enum employee_depart

it, operations, management, accounts, stores

};

struct employee_records

char name[10];

int employee_id;

float salary;

enum employee_depart emp;

};

struct employee_records em;

strcpy(em.name, "Debasif");

em.employee_id=546502;

em.salary=40000;

em.emp=management;

printf("Name of the employee=%s\n", em,name);

printf("“Employee id=%d\n", em.employee_id);

printf("Employee salary=%7.2f\n", em.salary);

printf("Employee department=%d\n", em.,emp);

getch();

}
Structures in C

What is a structure?
A structure is a user defined data type in C/C++. A structure creates a data type that can be used
to group items of possibly different types into a single type.

How to create a structure?


„struct‟ keyword is used to create a structure. Following is an example.

struct address

char name[50];

char street[100];

char city[50];

char state[20];

int pin;

};

How to declare structure variables?


A structure variable can either be declared with structure declaration or as a separate declaration
like basic types.

filter_none

brightness_4

// A variable declaration with structure declaration.

struct Point

int x, y;
} p1; // The variable p1 is declared with 'Point'

// A variable declaration like basic data types

struct Point

int x, y;

};

int main()

struct Point p1; // The variable p1 is declared like a normal variable

Note: In C++, the struct keyword is optional before in declaration of a variable. In C, it is


mandatory.

How to initialize structure members?


Structure members cannot be initialized with declaration. For example the following C program
fails in compilation.

filter_none

brightness_4

struct Point

int x = 0; // COMPILER ERROR: cannot initialize members here

int y = 0; // COMPILER ERROR: cannot initialize members here

};

The reason for above error is simple, when a datatype is declared, no memory is allocated
for it. Memory is allocated only when variables are created.
Structure members can be initialized using curly braces „{}‟. For example, following is a valid
initialization.

filter_none

brightness_4

struct Point

int x, y;

};

int main()

// A valid initialization. member x gets value 0 and y

// gets value 1. The order of declaration is followed.

struct Point p1 = {0, 1};

How to access structure elements?


Structure members are accessed using dot (.) operator.

#include<stdio.h>

struct Point

int x, y;

};

int main()

{
struct Point p1 = {0, 1};

// Accesing members of point p1

p1.x = 20;

printf ("x = %d, y = %d", p1.x, p1.y);

return 0;

Output:

x = 20, y = 1

What is designated Initialization?


Designated Initialization allows structure members to be initialized in any order. This feature has
been added in C99 standard.

#include<stdio.h>

struct Point

int x, y, z;

};

int main()

// Examples of initializtion using designated initialization

struct Point p1 = {.y = 0, .z = 1, .x = 2};

struct Point p2 = {.x = 20};

printf ("x = %d, y = %d, z = %d\n", p1.x, p1.y, p1.z);


printf ("x = %d", p2.x);

return 0;

Output:

x = 2, y = 0, z = 1
x = 20

This feature is not available in C++ and works only in C.

What is an array of structures?


Like other primitive data types, we can create an array of structures.

#include<stdio.h>

struct Point

int x, y;

};

int main()

// Create an array of structures

struct Point arr[10];

// Access array members

arr[0].x = 10;

arr[0].y = 20;

printf("%d %d", arr[0].x, arr[0].y);


return 0;

Output:

10 20

What is a structure pointer?


Like primitive types, we can have pointer to a structure. If we have a pointer to structure,
members are accessed using arrow ( -> ) operator.

#include<stdio.h>

struct Point

int x, y;

};

int main()

struct Point p1 = {1, 2};

// p2 is a pointer to structure p1

struct Point *p2 = &p1;

// Accessing structure members using structure pointer

printf("%d %d", p2->x, p2->y);

return 0;

Output:

1 2
Limitations of C Structures

In C language, Structures provide a method for packing together data of different types. A
Structure is a helpful tool to handle a group of logically related data items. However, C structures
have some limitations.

 The C structure does not allow the struct data type to be treated like built-in data types:

 We cannot use operators like +,- etc. on Structure variables. For example, consider the following code:

struct number

float x;

};

int main()

struct number n1,n2,n3;

n1.x=4;

n2.x=3;

n3=n1+n2;

return 0;

/*Output:

prog.c: In function 'main':

prog.c:10:7: error:

invalid operands to binary + (have 'struct number' and 'struct number')

n3=n1+n2;

*/

Das könnte Ihnen auch gefallen