Unit 2
Unit 2
.
Example
⚫ #include <stdio.h>
⚫ int main() {
⚫ int myAge = 43;
⚫ printf("%d\n", myAge);
⚫ printf("%p\n", &myAge);
⚫ return 0;
⚫ }
⚫ In the example above, &myAge is also known as
a pointer.
⚫ 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
.
#include <stdio.h>
int main() {
int myAge = 43; // An int variable
int* ptr = &myAge; // A pointer variable, with the name ptr,
that stores 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);
return 0;
}
⚫ 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.
Example
⚫ #include <stdio.h>
⚫ int main()
⚫ {
⚫ int a=10; //variable declaration
⚫ int *p; //pointer variable declaration
⚫ p=&a; //store address of variable a in pointer p
⚫ printf("Address stored in a variable p
is:%x\n",p); //accessing the address
⚫ printf("Value stored in a variable p is:%d\n",*p);
//accessing the value return 0;
⚫ }
Note:
.
pointers
⚫ ptr=&x
⚫ It assigns the address of x to ptr and
⚫ y=*ptr assigns the value pointed to by the
pointer ptr to y
⚫ *ptr=25
⚫ This statement puts the value of 25 at the
memory location whose address is the
value of ptr.
⚫ We know that the value of ptr is the
address of x and therefore old value of x is
replaced by 25.
Pointer increment and Scale Factor
.
Pointers and arrays
.
Pointers and arrays
Dereference
⚫ #include <stdio.h>
⚫ int main()
⚫ {
⚫ int x=9;
⚫ int *ptr;
⚫ ptr=&x;
⚫ *ptr=8;
⚫ printf("value of x is : %d", x);
⚫ return 0;
⚫ }
Dereference
⚫ #include <stdio.h>
⚫ int main() {
⚫ 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);
⚫ return 0;
⚫ }
Pointer to Pointer
.
Initialize a pointer
⚫ Initialize a pointer
⚫ After declaring a pointer, we initialize it like
standard variables with a variable address.
⚫ If pointers in C programming are not
uninitialized and used in the program, the results
are unpredictable and potentially disastrous.
⚫ To get the address of a variable, we use the and
(&)operator, placed before the name of a variable
whose address we need. Pointer initialization is
done with the following syntax.
⚫ Pointer Syntax
⚫ pointer = &variable;
Pointer operations
⚫ There are only a few operations that are
allowed to perform on Pointers in C
language.
⚫ The operations 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 of the same type
Increment/Decrement of a Pointer
⚫ #include <stdio.h>
⚫ struct Employee // create Employee structure
⚫ {
⚫ // define the member of the structure
⚫ char name[30];
⚫ int id;
⚫ int age;
⚫ char gender[30];
⚫ char city[40];
⚫ };
⚫ // define the variables of the Structure with pointers
⚫ struct Employee emp1, emp2, *ptr1, *ptr2;
⚫ int main()
⚫ {
⚫ ptr1 = &emp1; // store the address of the emp1 and emp2 structure
variable
⚫ ptr2 = &emp2;
⚫ printf (" Enter the name of the Employee
(emp1): ");
⚫ scanf (" %s", &ptr1->name);
⚫ printf (" Enter the id of the Employee (emp1): ");
⚫ scanf (" %d", &ptr1->id);
⚫ printf (" Enter the age of the Employee (emp1):
");
⚫ scanf (" %d", &ptr1->age);
⚫ printf (" Enter the gender of the Employee
(emp1): ");
⚫ scanf (" %s", &ptr1->gender);
⚫ printf (" Enter the city of the Employee (emp1):
");
⚫ scanf (" %s", &ptr1->city);
⚫ printf (" \n Second Employee: \n");
⚫ printf (" Enter the name of the Employee
(emp2): ");
⚫ scanf (" %s", &ptr2->name);
⚫ printf (" Enter the id of the Employee (emp2): ");
⚫ printf (" Enter the gender of the Employee (emp2): ");
⚫ scanf (" %s", &ptr2->gender);
⚫ printf (" Enter the city of the Employee (emp2): ");
⚫ scanf (" %s", &ptr2->city);
⚫ printf ("\n Display the Details of the Employee using Structure
Pointer");
⚫ printf ("\n Details of the Employee (emp1) \n");
⚫ printf(" Name: %s\n", ptr1->name);
⚫ printf(" Id: %d\n", ptr1->id);
⚫ printf(" Age: %d\n", ptr1->age);
⚫ printf(" Gender: %s\n", ptr1->gender);
⚫ printf(" City: %s\n", ptr1->city);
⚫ printf ("\n Details of the Employee (emp2) \n");
⚫ printf(" Name: %s\n", ptr2->name);
⚫ printf(" Id: %d\n", ptr2->id);
⚫ printf(" Age: %d\n", ptr2->age);
⚫ printf(" Gender: %s\n", ptr2->gender);
⚫ printf(" City: %s\n", ptr2->city);
⚫ return 0;
output
.
String
⚫ Strings are defined as an array of characters
⚫ The string can be defined as the one-dimensional array of
characters terminated by a null ('\0').
⚫ There are two ways to declare a string in c language.
⚫ 1.By char array
⚫ 2.By string literal
⚫ 1. string by char array :
⚫ char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
⚫ 2.string by the string literal :
⚫ char ch[]="javatpoint";
Strings
⚫ int main ()
⚫ {
⚫ char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
⚫ printf("Greeting message: %s\n", greeting );
⚫ return 0;
⚫ }
Example
⚫ To output the string, you can use
the printf() function together with the format
specifier %s to tell C that we are now working
with strings:
⚫ #include <stdio.h>
⚫ int main() {
⚫ char greetings[] = "Hello World!";
⚫ printf("%s", greetings);
⚫ return 0;
⚫ }
Access Strings
⚫ Access Strings
⚫ Since strings are actually arrays in C, you can
access a string by referring to its index
number inside square brackets [].
⚫ This example prints the first character
(0) in greetings:
⚫ Example
⚫ #include <stdio.h>
⚫ int main() {
⚫ char greetings[] = "Hello World!";
⚫ printf("%c", greetings[0]);
⚫ return 0;
⚫ }
Initializing a String:
⚫ A string can be initialized in different
ways.
The difference between a character array
and a string is ,the string is terminated
with a special character ‘\0’
1.char str[] = "GeeksforGeeks";
2. char str[50] = "GeeksforGeeks";
3. char str[] =
{'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
4. char str[14]
={'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
.
// C program to illustrate strings
⚫ #include<stdio.h>
⚫ int main()
⚫ {
⚫ // declare and initialize string
⚫ char str[] = "Geeks";
⚫ // print string
⚫ printf("%s",str);
⚫ return 0;
⚫ }
Modify Strings:
Example
⚫ #include<string.h>
⚫ int main (){
⚫ char a[50], b [50];
⚫ int d;
⚫ printf ("Enter 2 strings:");
⚫ scanf ("%s %s", a,b);
⚫ d = strcmp(a,b);
⚫ if (d==0){
⚫ printf("%s is (alphabetically) equal to %s", a,b);
⚫ }
⚫ else if (d>0){
⚫ printf("%s is (alphabetically) greater than %s",a,b); }
⚫ else if (d<0)
⚫ {
⚫ printf("%s is (alphabetically) less than %s", a,b);
⚫ }}
The strcmp () function
.
Example strstr() function
⚫ This function takes two strings s1 and s2 as an
argument and finds the first occurrence of the
sub-string s2 in the string s1. The process of
matching does not include the terminating
null-characters(‘\0’), but function stops there.
⚫ Syntax:
⚫ char *strstr (const char *s1, const char *s2);
⚫ Parameters: s1: This is the main string to be
examined. s2: This is the sub-string to be
searched in s1 string.
⚫ Return Value: This function returns a pointer
points to the first character of the
found s2 in s1 otherwise a null pointer if s2 is
not present in s1. If s2 points to an empty
string, s1 is returned.
C String Uppercase: strupr()
⚫ The strupr(string) function returns string
characters in uppercase.
⚫ #include<stdio.h>
⚫ #include <string.h>
⚫ int main(){
⚫ char str[20];
⚫ printf("Enter string: ");
⚫ gets(str);//reads string from console
⚫ printf("String is: %s",str);
⚫ printf("\nUpper String is: %s",strupr(str));
⚫ return 0;
⚫ }
String Lowercase: strlwr()
⚫ The strlwr(string) function returns string
characters in lowercase. Let's see a simple
example of strlwr() function.
⚫ #include <string.h>
⚫ int main(){
⚫ char str[20];
⚫ printf("Enter string: ");
⚫ gets(str);//reads string from console
⚫ printf("String is: %s",str);
⚫ printf("\nLower String is: %s",strlwr(str));
⚫ return 0;
⚫ }
C String Functions
⚫ There are many important string functions defined
in "string.h" library.
Structure
⚫ C Structures (structs)
⚫ 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.).
Structure in C
⚫ Structure in c is a user-defined data type
that enables us to store the collection of
different data types. Each element of a
structure is called a member.
⚫ The struct keyword is used to define the
structure.
Create a Structure
.
Example continued
Need of Structures
⚫ Heterogeneous collection of data
items: structure allows us to create user
defined data-type which can store items with
different data types.
⚫ Maintainability of code: using structure, we
represent complex records by using a single
name, which makes code maintainability
easy.
⚫ Enhanced code readability: code readability
is crucial for larger projects. Using structure
code looks user friendly which in turn helps
to maintain the project.
Example on Structure
⚫ #include <stdio.h>
⚫ struct Car {
⚫ char brand[50];
⚫ char model[50];
⚫ int year;
⚫ };
⚫ int main() {
⚫ struct Car car1 = {"BMW", "X5", 1999};
⚫ struct Car car2 = {"Ford", "Mustang", 1969};
⚫ struct Car car3 = {"Toyota", "Corolla", 2011};
⚫ printf("%s %s %d\n", car1.brand, car1.model, car1.year);
⚫ printf("%s %s %d\n", car2.brand, car2.model,
car2.year);
⚫ printf("%s %s %d\n", car3.brand, car3.model,
car3.year);
⚫ return 0;
⚫ }
Array of Structure
⚫ An array of structure is declared in same way
as we declare array of built in data type.
Example:
.
Array of structures
⚫ 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?
⚫ #include <stdio.h>
⚫ // Create a function
⚫ void myFunction() {
⚫ printf("I just got executed!");
⚫ }
⚫ int main() {
⚫ myFunction(); // call the function
⚫ return 0;
⚫ }
Function example
| Bitwise OR
^ Bitwise XOR
Bitwise
~
complement
Shift left