The document discusses pointers and arrays in C programming. It covers topics like passing arrays to functions, returning arrays from functions, and using pointers to access array elements. Examples are provided to demonstrate returning a sorted array from a function using pointers, calculating average of array elements by passing array to a function, and generating and returning an array of even numbers from a function. Pointers allow direct access to memory locations and are useful for array manipulation in C.
In computer science, a pointer is a programming language object, whose value refers to (or "points to") another value stored elsewhere in the computer memory using its memory address. A pointer references a location in memory, and obtaining the value stored at that location is known as dereferencing the pointer.
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address.
There are few important operations, which we will do with the help of pointers very frequently. (a) we define a pointer variable (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand.
In computer science, a pointer is a programming language object, whose value refers to (or "points to") another value stored elsewhere in the computer memory using its memory address. A pointer references a location in memory, and obtaining the value stored at that location is known as dereferencing the pointer.
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address.
There are few important operations, which we will do with the help of pointers very frequently. (a) we define a pointer variable (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand.
This Simplilearn tutorial will help you to learn the fundamentals of Pointers in C Programming. Pointers in C are used for file handling. This C Programming for Beginners tutorial will guide you to learn how to implement pointers for memory allocation, deallocation, reallocation, and other memory management operations.
C Programming/Strings. A string in C is merely an array of characters. The length of a string is determined by a terminating null character: '-' . So, a string with the contents, say, "abc" has four characters: 'a' , 'b' , 'c' , and the terminating null character.
Pointers in C language is a variable that stores/points the address of another variable. A Pointer in C is used to allocate memory dynamically i.e. at run time.
general use of pointer
what is pointer in c language
uses is pointer in c language
representation of pointer in c language
syantax of pointer in c language
program of pointer in c language
This Simplilearn tutorial will help you to learn the fundamentals of Pointers in C Programming. Pointers in C are used for file handling. This C Programming for Beginners tutorial will guide you to learn how to implement pointers for memory allocation, deallocation, reallocation, and other memory management operations.
C Programming/Strings. A string in C is merely an array of characters. The length of a string is determined by a terminating null character: '-' . So, a string with the contents, say, "abc" has four characters: 'a' , 'b' , 'c' , and the terminating null character.
Pointers in C language is a variable that stores/points the address of another variable. A Pointer in C is used to allocate memory dynamically i.e. at run time.
general use of pointer
what is pointer in c language
uses is pointer in c language
representation of pointer in c language
syantax of pointer in c language
program of pointer in c language
Declaring a PointerTo define a pointer, use an asterisk, (), in t.pdfmalavshah9013
Declaring a Pointer
To define a pointer, use an asterisk, (*), in the declaration to specify the variable will be a pointer
to the specified data type.
Recall that the name of an array holds the memory address of the first element of the array. The
second statement then would store the memory address of the first value in the variable valuePtr.
The name of a pointer is an identifier and must follow the rules for defining an identifier. Some
programmers place the letters ptr, a common abbreviation for pointer, at the end of the variable
name, others prefix a pointer with p_ or ptr_, and there are those who do nothing to distinguish a
pointer by its name. The naming of a pointer variable is a matter of programming style.
Once a pointer has been declared and initialized, it can be used to access the data to which it
points. In order to access this value, the dereference operator, *, must be used to prefix the name
of the pointer. From the code above, valuePtr holds the address of the first element of the values
array; therefore, *valuePtr will access the value 325. Add the following to main and execute the
program.
The output generated should look something like the following.
Where 0xbfad43e8 is a memory address displayed in hexadecimal.
Obtaining the Memory Address of a Variable
The address operator, &, is used to determine the memory address of a variable that is not an
array. Add code necessary to use fixed and setprecision, then add the following to main and run
the program to confirm the use of the address operator.
Using a Pointer to Alter Data
Just as the dereference operator is used to retrieve data, so too is it used to store data. Add the
following to function main and run the program.
The pointer, ratePtr, is used to change the data stored in payRate. The output of payRate
confirms the change.
Using a Pointer in an Expression
As previously shown, the value pointed to by a pointer variable can be retrieved by dereferencing
the pointer. In the above code, the retrieved value was simply displayed to the screen; however,
it can also be used in an expression. Add the following to main and execute the program.
Pointer Arithmetic
It is possible to add to or subtract from a memory address stored in a pointer. These actions can
be accomplished using the addition operator,+, subtraction operator, - and the increment and
decrement operators, ++ and --. This is helpful when accessing arrays via pointers.
The increment operator has been used to add the value 1 to a variable. When used with a pointer,
the increment operator adds the size of the data referenced to the memory address stored in the
pointer, effectively moving the pointer to the next data value. Building on the code from above,
add the following to main and execute the program.
We initialized valuePtr to the memory address of the first element of the array values.
Incrementing valuePtr instructs the computer to add four bytes, the size of an integer, to the
memory addressed stored in .
U3_4_PointerArithmetic.pdf people will use the above preaentationa dnmit23cs
Which of the following statements about selfishness/unselfishness is/are INCORRECT?
1. The same action under one set of circumstances may be unselfish, and under another set quite selfish.
2. True freedom can’t be attained by perfect unselfishness.
3. Whatever is the source of religion/ethics, the central idea is to constantly think of the puny, little self.
Only 1 & 2
Only 2&3
Only 1 & 3
All 1,2 & 3
Which of the following statements about selfishness/unselfishness is/are INCORRECT?
1. The same action under one set of circumstances may be unselfish, and under another set quite selfish.
2. True freedom can’t be attained by perfect unselfishness.
3. Whatever is the source of religion/ethics, the central idea is to constantly think of the puny, little self.
Only 1 & 2
Only 2&3
Only 1 & 3
All 1,2 & 3
Which of the following statements about selfishness/unselfishness is/are INCORRECT?
1. The same action under one set of circumstances may be unselfish, and under another set quite selfish.
2. True freedom can’t be attained by perfect unselfishness.
3. Whatever is the source of religion/ethics, the central idea is to constantly think of the puny, little self.
Only 1 & 2
Only 2&3
Only 1 & 3
All 1,2 & 3
Which of the following statements about selfishness/unselfishness is/are INCORRECT?
1. The same action under one set of circumstances may be unselfish, and under another set quite selfish.
2. True freedom can’t be attained by perfect unselfishness.
3. Whatever is the source of religion/ethics, the central idea is to constantly think of the puny, little self.
Only 1 & 2
Only 2&3
Only 1 & 3
All 1,2 & 3
Which of the following statements about selfishness/unselfishness is/are INCORRECT?
1. The same action under one set of circumstances may be unselfish, and under another set quite selfish.
2. True freedom can’t be attained by perfect unselfishness.
3. Whatever is the source of religion/ethics, the central idea is to constantly think of the puny, little self.
Only 1 & 2
Only 2&3
Only 1 & 3
All 1,2 & 3
Which of the following statements about selfishness/unselfishness is/are INCORRECT?
1. The same action under one set of circumstances may be unselfish, and under another set quite selfish.
2. True freedom can’t be attained by perfect unselfishness.
3. Whatever is the source of religion/ethics, the central idea is to constantly think of the puny, little self.
Only 1 & 2
Only 2&3
Only 1 & 3
All 1,2 & 3
Which of the following statements about selfishness/unselfishness is/are INCORRECT?
1. The same action under one set of circumstances may be unselfish, and under another set quite selfish.
2. True freedom can’t be attained by perfect unselfishness.
3. Whatever is the source of religion/ethics, the central idea is to constantly think of the puny, little self.
Only 1 & 2
Only 2&3
Only 1 & 3
All 1,2 & 3
Which of the following statements about selfishness/unselfishness is/are INCORRECT?
1. The same action under one set of circumstances may
Similar to C Programming : Pointers and Arrays, Pointers and Strings (20)
This PPT is very much useful for practitioners who are all making products and services to society. Mangers think innovatively and come up with innovative ideas. It is a 5 stage processing also called a design thinking process. The stages are empathize, define, ideate, prototype and test.
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERSveerababupersonal22
It consists of cw radar and fmcw radar ,range measurement,if amplifier and fmcw altimeterThe CW radar operates using continuous wave transmission, while the FMCW radar employs frequency-modulated continuous wave technology. Range measurement is a crucial aspect of radar systems, providing information about the distance to a target. The IF amplifier plays a key role in signal processing, amplifying intermediate frequency signals for further analysis. The FMCW altimeter utilizes frequency-modulated continuous wave technology to accurately measure altitude above a reference point.
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdffxintegritypublishin
Advancements in technology unveil a myriad of electrical and electronic breakthroughs geared towards efficiently harnessing limited resources to meet human energy demands. The optimization of hybrid solar PV panels and pumped hydro energy supply systems plays a pivotal role in utilizing natural resources effectively. This initiative not only benefits humanity but also fosters environmental sustainability. The study investigated the design optimization of these hybrid systems, focusing on understanding solar radiation patterns, identifying geographical influences on solar radiation, formulating a mathematical model for system optimization, and determining the optimal configuration of PV panels and pumped hydro storage. Through a comparative analysis approach and eight weeks of data collection, the study addressed key research questions related to solar radiation patterns and optimal system design. The findings highlighted regions with heightened solar radiation levels, showcasing substantial potential for power generation and emphasizing the system's efficiency. Optimizing system design significantly boosted power generation, promoted renewable energy utilization, and enhanced energy storage capacity. The study underscored the benefits of optimizing hybrid solar PV panels and pumped hydro energy supply systems for sustainable energy usage. Optimizing the design of solar PV panels and pumped hydro energy supply systems as examined across diverse climatic conditions in a developing country, not only enhances power generation but also improves the integration of renewable energy sources and boosts energy storage capacities, particularly beneficial for less economically prosperous regions. Additionally, the study provides valuable insights for advancing energy research in economically viable areas. Recommendations included conducting site-specific assessments, utilizing advanced modeling tools, implementing regular maintenance protocols, and enhancing communication among system components.
Forklift Classes Overview by Intella PartsIntella Parts
Discover the different forklift classes and their specific applications. Learn how to choose the right forklift for your needs to ensure safety, efficiency, and compliance in your operations.
For more technical information, visit our website https://intellaparts.com
Final project report on grocery store management system..pdfKamal Acharya
In today’s fast-changing business environment, it’s extremely important to be able to respond to client needs in the most effective and timely manner. If your customers wish to see your business online and have instant access to your products or services.
Online Grocery Store is an e-commerce website, which retails various grocery products. This project allows viewing various products available enables registered users to purchase desired products instantly using Paytm, UPI payment processor (Instant Pay) and also can place order by using Cash on Delivery (Pay Later) option. This project provides an easy access to Administrators and Managers to view orders placed using Pay Later and Instant Pay options.
In order to develop an e-commerce website, a number of Technologies must be studied and understood. These include multi-tiered architecture, server and client-side scripting techniques, implementation technologies, programming language (such as PHP, HTML, CSS, JavaScript) and MySQL relational databases. This is a project with the objective to develop a basic website where a consumer is provided with a shopping cart website and also to know about the technologies used to develop such a website.
This document will discuss each of the underlying technologies to create and implement an e- commerce website.
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Dr.Costas Sachpazis
Terzaghi's soil bearing capacity theory, developed by Karl Terzaghi, is a fundamental principle in geotechnical engineering used to determine the bearing capacity of shallow foundations. This theory provides a method to calculate the ultimate bearing capacity of soil, which is the maximum load per unit area that the soil can support without undergoing shear failure. The Calculation HTML Code included.
Using recycled concrete aggregates (RCA) for pavements is crucial to achieving sustainability. Implementing RCA for new pavement can minimize carbon footprint, conserve natural resources, reduce harmful emissions, and lower life cycle costs. Compared to natural aggregate (NA), RCA pavement has fewer comprehensive studies and sustainability assessments.
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)MdTanvirMahtab2
This presentation is about the working procedure of Shahjalal Fertilizer Company Limited (SFCL). A Govt. owned Company of Bangladesh Chemical Industries Corporation under Ministry of Industries.
Saudi Arabia stands as a titan in the global energy landscape, renowned for its abundant oil and gas resources. It's the largest exporter of petroleum and holds some of the world's most significant reserves. Let's delve into the top 10 oil and gas projects shaping Saudi Arabia's energy future in 2024.
Immunizing Image Classifiers Against Localized Adversary Attacksgerogepatton
This paper addresses the vulnerability of deep learning models, particularly convolutional neural networks
(CNN)s, to adversarial attacks and presents a proactive training technique designed to counter them. We
introduce a novel volumization algorithm, which transforms 2D images into 3D volumetric representations.
When combined with 3D convolution and deep curriculum learning optimization (CLO), itsignificantly improves
the immunity of models against localized universal attacks by up to 40%. We evaluate our proposed approach
using contemporary CNN architectures and the modified Canadian Institute for Advanced Research (CIFAR-10
and CIFAR-100) and ImageNet Large Scale Visual Recognition Challenge (ILSVRC12) datasets, showcasing
accuracy improvements over previous techniques. The results indicate that the combination of the volumetric
input and curriculum learning holds significant promise for mitigating adversarial attacks without necessitating
adversary training.
Cosmetic shop management system project report.pdfKamal Acharya
Buying new cosmetic products is difficult. It can even be scary for those who have sensitive skin and are prone to skin trouble. The information needed to alleviate this problem is on the back of each product, but it's thought to interpret those ingredient lists unless you have a background in chemistry.
Instead of buying and hoping for the best, we can use data science to help us predict which products may be good fits for us. It includes various function programs to do the above mentioned tasks.
Data file handling has been effectively used in the program.
The automated cosmetic shop management system should deal with the automation of general workflow and administration process of the shop. The main processes of the system focus on customer's request where the system is able to search the most appropriate products and deliver it to the customers. It should help the employees to quickly identify the list of cosmetic product that have reached the minimum quantity and also keep a track of expired date for each cosmetic product. It should help the employees to find the rack number in which the product is placed.It is also Faster and more efficient way.
Cosmetic shop management system project report.pdf
C Programming : Pointers and Arrays, Pointers and Strings
1. UNIT I : Pointers and Arrays, Pointers
and Strings
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
5. Text Book and Reference Book
4/21/2021 1.0 _ Pointers and Arrays 5
6. Unit I : Contents
1. Pointers- Introduction
2. Pointers and 1D array
3. Passing an array to a function
4. Returning an array from function
5. NULL pointers
6. Array of pointers
7. Pointer-to-pointer
8. Pointers and 2D array
9. Generic pointers
10. Dangling Pointer
11. Using Pointers for string manipulation
12. Two dimensional array of strings
13. Array of pointers to strings.
4/21/2021 6
1.0 _ Pointers and Arrays
7. Pointers- Introduction
• Every variable in C language has a name and a
value associated with it.
• When a variable is declared, a specific block
of memory within the computer is allocated
to hold the value of that variable.
• Each memory location has a distinct address.
4/21/2021 1.0 _ Pointers and Arrays 7
8. Pointers- Introduction
• For example,
– we live in a house and our house has an address,
which helps other people to identify our house.
• The same way the value of the variable is
identified using the address of that variable.
• This address of the variable or memory location
can be stored in a pointer.
4/21/2021 1.0 _ Pointers and Arrays 8
9. Pointers- Introduction
• Using pointer we can have direct access to a
memory location because they store address
of a variable or memory location.
• Pointers are closely related to low level
memory operations.
• Before introducing the pointers in
programming, let us understand what
happens during a variable definition.
4/21/2021 1.0 _ Pointers and Arrays 9
10. Pointers- Introduction
• Let us consider the following statement :
• When the above statement is compiled and
executed, the following will happen:
– The compiler allocates memory to store an integer.
– Next , compiler assigns a label to the allocated
memory location as n.
– Finally, the constant 10 is stored in that location.
4/21/2021 1.0 _ Pointers and Arrays 10
11. Advantages of Pointers
• Pointers provide direct access to memory.
• Pointers are used to return more than one value from
a function.
• Pointers allow dynamic memory allocation and
deallocation.
• Reduces the storage space required by the program.
• Pointers are more efficient in handling arrays and
structures.
• Pointers are used to get reference of a variable or
function.
• Pointers increases program execution speed.
• Pointer allows to create complex data structures such
as linked list, stack, queues, trees, graphs etc.
4/21/2021 1.0 _ Pointers and Arrays 11
12. Pointers- Introduction
• Pointer is a variable which stores the address
of another variable.
• It is used to allocate memory dynamically.
• Memory allocation done at run time is known
as Dynamic memory allocation.
• Pointer variable may be any valid C data type
such as int, float, double, char etc.
• For any type of pointers, only four bytes of
memory is allocated for storing the address.
4/21/2021 1.0 _ Pointers and Arrays 12
14. Pointer Declaration
4/21/2021 1.0 _ Pointers and Arrays 14
• Pointer can be declared with a variable preceded by *.
• Pointer can be declared using the following syntax:
15. Pointer operators
• Reference or Address of operator (&)
• Dereference operator or indirection operator
or Value at Address Operator (*)
4/21/2021 1.0 _ Pointers and Arrays 15
17. Dereference operator (*)
• To access the value at the address stored in the
pointer variable, we can use dereference
operator (*).
• This is an unary operator * that returns the value
of the variable located at the address specified by
its operand.
4/21/2021 1.0 _ Pointers and Arrays 17
21. Swapping using function and pointers
• we have to use pointers concept.
• Bz,
– Parameters are always passed by value in C and
– function can not return more than one value.
4/21/2021 1.0 _ Pointers and Arrays 21
24. Pointer Arithmetic
• A pointer is a variable which holds the address of another
variable.
• Address is represented by a numeric value.
• We cannot perform every type of arithmetic operation on
pointers.
• The following arithmetic operations are the only valid
arithmetic operations performed on pointers:
4/21/2021 1.0 _ Pointers and Arrays 24
25. Pointer Arithmetic
• For example, assume the integer pointer ptr
which contains the address 1000.
• If we are incrementing the pointer ptr by 1 (using
++ptr or ptr++), we will get 1002 (i.e 1000 + 1 * 2)
• Instead of 1001 because the size of the int data
type is 2 bytes (Note: Size of the datatype
changes depends on the compiler used).
• If we are using a system where the size of int is 4
bytes then we would get 1004 ( i.e 1000 + 1 * 4 ).
4/21/2021 1.0 _ Pointers and Arrays 25
26. Pointer Arithmetic - Example
• Suppose the address of the variables i, f and ch are
1000, 2000 , 3000 respectively. Therefore iptr, fptr and
cptr will have initial values of 1000, 2000 and 3000.
Assume 1, 2 and 4 bytes of memory is allocated for
char, int and float variables respectively.
4/21/2021 1.0 _ Pointers and Arrays 26
30. Example 4 - Print all the alphabets using pointer
4/21/2021 1.0 _ Pointers and Arrays 30
31. Example 5 - Add two integers using pointers
4/21/2021 1.0 _ Pointers and Arrays 31
32. Example 6 - Add two integers using function by
passing address of two numbers as arguments
to function.
4/21/2021 1.0 _ Pointers and Arrays 32
33. Pointer Arithmetic between Two Pointers
• Arithmetic operation between two pointers is
performed only on same type of pointers.
• Let us take two integer pointers ptr1 and ptr2
with addresses 1000 and 1008 respectively.
• The expression ptr2 - ptr1 will give the result
as 4, since the memory location allocated for
integer data type is 2 bytes.
• If we subtract ptr2 from ptr1 i.e the
expression (ptr1 - ptr2) will give the result -4.
4/21/2021 1.0 _ Pointers and Arrays 33
36. UNIT I : Pointers and Arrays, Pointers
and Strings
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
37. Unit I : Contents
1. Pointers- Introduction
2. Pointers and 1D array
3. Passing an array to a function
4. Returning an array from function
5. NULL pointers
6. Array of pointers
7. Pointer-to-pointer
8. Pointers and 2D array
9. Generic pointers
10. Dangling Pointer
11. Using Pointers for string manipulation
12. Two dimensional array of strings
13. Array of pointers to strings.
4/21/2021 37
2.0 _ Pointers and Arrays
38. Pointers and Arrays
• We are already familiar with arrays, which store multiple values of
the same data type.
• Array elements are stored in contiguous memory locations.
• When an array is declared, compiler allocates required amount of
contiguous memory locations to hold all the elements of the array.
• Memory is allocated by the compiler during compilation time itself.
• Base address of the array is the address of the first element of the
array.
• We can create a pointer which can be used to point an array.
• In an one dimensional array, we can use single subscript to access
the array elements.
• Name of the 1-D array or &array[0] points to the address of the
first element of an array.
4/21/2021 2.0 _ Pointers and Arrays 38
39. Pointers and 1D Arrays
• Suppose we declare an integer array “A” with 5
elements and assuming that the base address of the
array a is 1000 and each integer element requires two
bytes of memory.
• The five elements will be stored as follows:
• Here array name “A” acts as a constant pointer which
will give the base address of the array and points to
the first element of the array, A[0].
– i.e., the value of A and &A[0] are same.
4/21/2021 2.0 _ Pointers and Arrays 39
40. Pointers and 1D Arrays
• We can declare another pointer of type int to point to the
array A.
• Now we can access every element of the array A using
pointer p.
• (*p) is used to access the element A[0] which has the value
1 in the given example.
• To access the next element in the array A,
– increment the pointer p by 1 using (p++) or (++p).
– Now we can give *p to get A[1].
– It gives the value 2.
– To get the next element in the array A, increment the pointer p
by 1 and use *p.
4/21/2021 2.0 _ Pointers and Arrays 40
41. Example 1- Program to demonstrates the use of
pointer to access the array elements
4/21/2021 2.0 _ Pointers and Arrays 41
42. Example 2- use array name as a pointer to
access the array elements
4/21/2021 2.0 _ Pointers and Arrays 42
43. • In the above program, A is a constant pointer which always
points to first element A[0].
• We cannot move this pointer to next element using ++
operator since base address of the array cannot be
changed.
• To access the elements of the array using a constant
pointer A, we can use the following statements:
4/21/2021 2.0 _ Pointers and Arrays 43
44. Example 3- Program to display the elements of
an array in reverse order using pointer.
4/21/2021 2.0 _ Pointers and Arrays 44
45. Example 4 – Program to add the elements of an
array using pointer
4/21/2021 2.0 _ Pointers and Arrays 45
46. Example 5 – Program to demonstrate increment and
decrement operators with pointers and arrays.
4/21/2021 2.0 _ Pointers and Arrays 46
47. Example 6 - Program to copy an array to another array
using pointers
4/21/2021 2.0 _ Pointers and Arrays 47
49. UNIT I : Pointers and Arrays, Pointers
and Strings
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
50. Unit I : Contents
1. Pointers- Introduction
2. Pointers and 1D array
3. Passing an array to a function
4. Returning an array from function
5. Pointers and 2D array
6. NULL pointers
7. Array of pointers
8. Pointer-to-pointer
9. Generic pointers
10. Dangling Pointer
11. Using Pointers for string manipulation
12. Two dimensional array of strings
13. Array of pointers to strings.
4/21/2021 50
2.0 _ Passing and Returing an array
to_from a function
51. Passing an array to a function
• We can pass an individual elements or entire
array to a function as an argument.
• To pass an entire array to a function, only the
name of the array is passed as an argument.
• When address is passed as an argument, the
function definition should have an array or a
pointer as a parameter to receive the passed
address.
• When an array is passed to a function, the
changes made by the function affect the original
array.
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
51
52. Function Definition with array as a
parameter
• We can receive an array in a function using one of
the following two methods.
• The name of the array is passes as an argument,
which is the address of the first element of the
array.
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
52
53. Example 1 – Program to demonstrate the
average of all the elements of an array.
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
53
57. Example 2 - Write a program in C to
sort an array using Pointer
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
57
58. Returning an array from a function
• C does not allow to return an entire array
from a function.
• However, we can return a pointer to the base
address(address of first element of array) of
an array by specifying the name of the array
without an index.
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
58
59. Returning an array from a function
• If we want to return a 1-D array from a
function, we have to declare a function
returning a pointer as in the following
example :
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
59
60. Returning an array from a function
• We should not return base pointer of a local
array declared inside a function because as
soon as control returns from a function all
local variables gets destroyed.
• If we want to return a local array then we
should declare it as a static variable so that it
retains it's value after function call.
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
60
61. Example 2 - Program to generate first N
even numbers and return as an array.
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
61
64. UNIT I : Pointers and Arrays, Pointers
and Strings
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
65. Unit I : Contents
1. Pointers- Introduction
2. Pointers and 1D array
3. Passing an array to a function
4. Returning an array from function
5. Pointers and 2D array
6. Array of pointers
7. NULL pointers
8. Pointer-to-pointer
9. Generic pointers
10. Dangling Pointer
11. Using Pointers for string manipulation
12. Two dimensional array of strings
13. Array of pointers to strings.
4/21/2021 65
1.4 _ Pointers and 2D Arrays
66. Pointers and 2D array
• In a two dimensional array, we can access
each element by using two subscripts.
– first subscript represents the row number and
– second subscript represents the column number
• Consider the following declaration statement,
4/21/2021 1.4 _ Pointers and 2D Arrays 66
67. Pointers and 2D array
• The above declaration statement creates a
3x4 matrix initialized with the following
values:
4/21/2021 1.4 _ Pointers and 2D Arrays 67
68. Pointers and 2D array
• The element at ith row, jth column can be accessed
using a[i][j].
• To access the value 7, we have to use a[1][2].
• Let us see how pointer is used to access the 2-D array.
• As we know, name of the array gives the base address
of the array i.e., address of a[0][0].
• To access a[i][j] using base pointer of the array, we can
use the following generalized form:
4/21/2021 1.4 _ Pointers and 2D Arrays 68
69. Pointers and 2D array
• The following figure shows how the above 2-D array
will be stored in memory.
• Array elements are stored in memory row by row.
4/21/2021 1.4 _ Pointers and 2D Arrays 69
70. Pointers and 2D array
• In a 2-D array, each row will be considered as a one
dimensional array.
• Hence 2-D array can be considered as a collection of
several one dimensional arrays.
• In this example, each row is an array of 4 integers.
• We know that the name of an array is a constant pointer
that points to 0th row which contains address 1000.
4/21/2021 1.4 _ Pointers and 2D Arrays 70
71. Pointers and 2D array
4/21/2021 1.4 _ Pointers and 2D Arrays 71
72. Pointers and 2D array
• Consider a two dimensional array mat[ROWS] [COLS]
where ROWS and COLS are some integer value.
• We can use any one of the following two notations to
access the two dimensional array.
• The first int mat[][COLS] is general array notation.
• Whereas int (*mat)[COLS] is a pointer to array.
4/21/2021 1.4 _ Pointers and 2D Arrays 72
73. Example - read and display a 3x3 matrix
4/21/2021 1.4 _ Pointers and 2D Arrays 73
74. Passing a 2D array to a function
• For passing multidimensional arrays,
– First array dimension does not have to be
specified.
– The second dimension must be explicitly
specified or a pointer to pointer as a parameter
to receive the address.
4/21/2021 1.4 _ Pointers and 2D Arrays 74
75. Example - print 2-D array using function
4/21/2021 1.4 _ Pointers and 2D Arrays 75
76. Example - add two 3 x 3 matrices using pointer
4/21/2021 1.4 _ Pointers and 2D Arrays 76
91. Returning a 2D array from Function
• Returning a 2D array from function is not as straight as
passing an array to a function.
• Arrays in C are passed by reference, hence any changes
made to array passed as argument persists after the
function.
• So you can accept the output array you need to return, as a
parameter to the function.
• The following program demonstrates how a 2-D array is
returned from a function by passing resultant array also as
a parameter.
• In the following program, main() receives two matrices as
input and these two matrices along with resultant matrix
are passed as arguments to the function sum().
• The sum() function adds the two matrices and return the
resultant matrix as result to the main() function.
4/21/2021 1.4 _ Pointers and 2D Arrays 91
97. Further Reference
To
Pass and Return an array(1D & 2D) to / from function
with/without using pointers
please refer
this
link......
• https://codeforwin.org/2017/12/pass-return-
array-function-c.html#return-array-multi
4/21/2021 1.4 _ Pointers and 2D Arrays 97
99. UNIT I : Pointers and Arrays, Pointers
and Strings
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
100. Unit I : Contents
1. Pointers- Introduction
2. Pointers and 1D array
3. Passing an array to a function
4. Returning an array from function
5. Pointers and 2D array
6. Array of pointers
7. NULL pointers
8. Pointer-to-pointer
9. Generic pointers
10. Dangling Pointer
11. Using Pointers for string manipulation
12. Two dimensional array of strings
13. Array of pointers to strings.
4/21/2021 100
1.5 _ Pointers Concepts
101. Array of Pointers
• When we want to maintain an array to store the
address of memory locations of type int or float
or char or any other data type available, we have
to create an array of pointers.
• Here is the syntax to declare an array of pointers
which is almost same as that of declaring an
array of int, float or char etc.,
4/21/2021 1.5 _ Pointers Concepts 101
102. Array of Pointers
• Here ptr is an array of 5 integer pointers ie., the
integer pointers are ptr[0], ptr[1] ….ptr[4].
• Each element in this array can hold the address of
an integer variable.
4/21/2021 1.5 _ Pointers Concepts 102
104. NULL Pointer
• Pointer is assigned a value NULL if it is not
assigned any valid address of the memory.
• NULL pointer is a pointer which points to
nothing.
• Pointer is initialized with a value NULL or 0
regardless of the pointer type.
4/21/2021 1.5 _ Pointers Concepts 104
106. Uses of NULL pointer
• If no valid memory address is available to store it
in a pointer, initialize a pointer with NULL.
• If pointer is used in a function block, before
using it, check whether the pointer is not a NULL
value.
• Make a habit of initializing a pointer before
using it.
• Initialize a pointer with a valid address or NULL.
4/21/2021 1.5 _ Pointers Concepts 106
108. Pointer to a Pointer
• C supports a pointer that points to another
pointer.
• This pointer in turn can point to another
pointer, and so on.
• At the simplest level, a pointer to a pointer is
declared in this manner:
4/21/2021 1.5 _ Pointers Concepts 108
109. Pointer to a Pointer
4/21/2021 1.5 _ Pointers Concepts 109
110. Pointer to a Pointer
• This pointer currently points nowhere. It can
be completely dereferenced after
– (i) pointing q to a pointer variable, say, p, and
– (ii) pointing p to another object, say, the simple
variable x.
• Thus, if p = &x and q = &p, then the value of x
can be evaluated using double indirection:
4/21/2021 1.5 _ Pointers Concepts 110
111. Pointer to a Pointer
• This expression can be interpreted as *(*q),
which means using the dereferencing
operator twice.
• You need to use an extra * for every
additional level of indirection.
• Thus, you can create a pointer to q, say, r, and
then use ***r or **q or *p to evaluate x.
4/21/2021 1.5 _ Pointers Concepts 111
114. Uses and Caution of **P
• Why do we need pointer-to-pointers?
• Can a function that swaps two regular variables
be used to swap two pointers?
– No, it can’t because the function will swap the copies
of these pointers.
– The solution obviously lies in the use of pointer-to-
pointers as function arguments.
• double-indirection pointers are
– Implicitly used in handling 2D arrays.
– Explicitly used in applications that need to
manipulate pointer values inside a function.
4/21/2021 1.5 _ Pointers Concepts 114
115. Generic Pointer (or) void Pointer
• There is no data type associated with generic
pointer.
• It can be used to store address of any data
type and it can be converted to any type
using type casting.
• void pointers cannot be dereferenced.
• Generic pointer can be declared using the
keyword void.
4/21/2021 1.5 _ Pointers Concepts 115
117. Dangling Pointer
4/21/2021 1.5 _ Pointers Concepts 117
• Even though the memory block is freed, it is still
accessible because the pointer to it is not lost
(dangling pointer).
• Dangling pointers arise during object destruction,
when an object that has an incoming reference is
deleted or deallocated, without modifying the value of
the pointer, so that the pointer still points to the
memory location of the deallocated memory.
118. Dangling Pointer
• Freeing a memory block with free(p) doesn’t
necessarily make it inaccessible because p continues
to point to the block. p is now a dangling pointer.
• As a safety measure, it should be set to NULL
immediately after invoking free.
• Because this memory—partially or totally—may have
already been allocated, a subsequent attempt to
access it using p could produce erroneous results or
even cause the program to crash.
• Setting p to NULL solves the problem easily.
4/21/2021 1.5 _ Pointers Concepts 118
119. Dangling Pointer
• A pointer pointing to a memory location that
has been deleted (or freed) is called dangling
pointer.
• There are three different ways where Pointer
acts as dangling pointer:
– De-allocation of memory
– Function Call
– Variable goes out of scope
4/21/2021 1.5 _ Pointers Concepts 119
122. Example – Function Call - Solution
4/21/2021 1.5 _ Pointers Concepts 122
123. Example – Variable goes out of scope
4/21/2021 1.5 _ Pointers Concepts 123
124. Wild Pointer
• A pointer which has not been initialized to
anything (not even NULL) is known as wild
pointer.
• The pointer may be initialized to a non-NULL
garbage value that may not be a valid address.
4/21/2021 1.5 _ Pointers Concepts 124
126. UNIT I : Pointers and Arrays, Pointers
and Strings
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
127. Unit I : Contents
1. Pointers- Introduction
2. Pointers and 1D array
3. Passing an array to a function
4. Returning an array from function
5. Pointers and 2D array
6. Array of pointers
7. NULL pointers
8. Pointer-to-pointer
9. Generic pointers
10. Dangling Pointer
11. Using Pointers for string manipulation
12. Two dimensional array of strings
13. Array of pointers to strings.
4/21/2021 127
1.6 _ Pointers and Strings
128. Pointers and Strings
• Strings are defined as arrays of characters.
• In order to allow variable length strings, the
string should be terminated by ‘0’ which is used
to indicate the end of a string.
• For example, the following program segment
declares a string s of 10 characters and assign the
starting address of string s into pointer ptr.
4/21/2021 1.6 _ Pointers and Strings 128
129. Pointers and Strings
• Three things will happen when we create the
below array.
– 10 memory locations are allocated for the array.
– The string “Hello” is stored in first 5 locations and in
the sixth location ‘0’ is automatically stored to
indicate the end of the string.
– The pointer ptr points at the first location of the
allocated memory
4/21/2021 1.6 _ Pointers and Strings 129
130. Example – program to use pointer to
print the string array
4/21/2021 1.6 _ Pointers and Strings 130
131. display the string using pointer with
“%s” as the formatting character
4/21/2021 1.6 _ Pointers and Strings 131
132. Example 2 - to count vowels and consonants in a string
using pointer
4/21/2021 1.6 _ Pointers and Strings 132
133. Example 3 - to find the length of the given string
4/21/2021 1.6 _ Pointers and Strings 133
135. create a list of strings
• When we want to create a list of strings, We
can use the following methods:
– Two dimensional character array
– Array of Pointers to Strings
4/21/2021 1.6 _ Pointers and Strings 135
136. Two dimensional character array
• The following program demonstrates the use of
2-D array to store the list of cities. It allocates
memory for storing 4 cities and for each city 10
locations are allocated.
4/21/2021 1.6 _ Pointers and Strings 136
140. Array of Pointers to Strings
• When we want to store multiple strings, we
can create array of pointers and we can make
each pointer points to one string.
• Suppose there are N elements in an array, we
can make each element to point to one string.
4/21/2021 1.6 _ Pointers and Strings 140
141. Array of Pointers to Strings
• we have learned how we can use an array of
strings or 2-D array of characters.
• It may appear to you whenever you need to
store more than one string then an array of
strings is the way to go, unfortunately, this is
not the case.
• Consider the following example.
4/21/2021 1.6 _ Pointers and Strings 141
142. Array of Pointers to Strings
4/21/2021 1.6 _ Pointers and Strings 142
143. Array of Pointers to Strings
• As you can see not all strings are long enough to fill all
the rows of the array, that's why compiler fills these
empty spaces (highlighted using light grey color) with
the null characters ('0').
• The total size of the sports array is 75 bytes but
only 34 bytes is used, 41 bytes is wasted.
• 41 bytes may not appear much but in a large program,
a considerable amount of bytes would be wasted.
• What we need is a jagged array: A 2-D array whose
rows can be of different length.
• C doesn't provide jagged arrays but we can simulate
them using an array of pointer to a string.
4/21/2021 1.6 _ Pointers and Strings 143
144. Array of Pointers to Strings
• An array of pointers to strings is an array of
character pointers where each pointer points
to the first character of the string or the base
address of the string.
• Let's see how we can declare and initialize an
array of pointers to strings.
4/21/2021 1.6 _ Pointers and Strings 144
145. Array of Pointers to Strings
4/21/2021 1.6 _ Pointers and Strings 145
146. Array of Pointers to Strings
• Here sports is an array of pointers to strings.
• If initialization of an array is done at the time of
declaration then we can omit the size of an
array.
• So the above statement can also be written as:
4/21/2021 1.6 _ Pointers and Strings 146
147. Array of Pointers to Strings
• It is important to note that each element of
the sports array is a string literal and since a
string literal points to the base address of the
first character.
• The 0th element i.e arr[0] points to the base
address of string "golf".
• Similarly, the 1st element i.e arr[1] points to
the base address of string "hockey" and so on.
4/21/2021 1.6 _ Pointers and Strings 147
148. • Here is how an array of pointers to string is
stored in memory.
4/21/2021 1.6 _ Pointers and Strings 148
Array of Pointers to Strings
149. Array of Pointers to Strings
• 34 + 20 = 54.
• In this case, all string literals occupy 34 bytes
and 20 bytes are occupied by the array of
pointers i.e sports.
• So, just by creating an array of pointers to
string instead of array 2-D array of characters
we are saving 21 bytes (75-54=21) of memory
4/21/2021 1.6 _ Pointers and Strings 149
152. Example 2 - Array of Pointers to Strings
• The following program demonstrates the use of
array of pointers to store the list of cities.
• Each pointer in the array can point to one city
name.
• It allocates memory for
– 1) storing the address of four strings
• ( 4 x 4 = 16 locations)
– 2) required memory locations
• (ie., Number of characters in the string + 1 location for
storing ‘0’ character) are allocated for each city.
4/21/2021 1.6 _ Pointers and Strings 152