This document outlines pointers and related concepts in C programming. It begins with an introduction to pointers, noting they are powerful but difficult to master. It then covers pointer variable declarations and initialization, the pointer operators & and *, calling functions by reference using pointers, and using const with pointers. Later sections discuss pointer expressions and arithmetic, the relationship between pointers and arrays, arrays of pointers, and pointers to functions. The document provides examples to illustrate key pointer concepts.
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 Presentation gives you all knowledge about #CPointers, #PointersInC.
The given slides are as follows:
1. Introduction of Pointers.
2. Systems to create a pointer in C.
3. Valid Pointer Examples in C.
4. Graphical representation of address assigning in c using pointer.
5. 1st Sample program of pointers in C.
6. Types of Pointers
7. NULL Pointer in C (Types of Pointer)
8. void Pointer in C (Types of Pointer)
9. Wild Pointer in C (Types of Pointer)
10. Changing value of variable using pointer
11. Update and Access value of variable using pointer in example.
12. Types of format specifies to print address in different format.
13. Advantages of Pointer in C.
14. Disadvantages of Pointer in C.
15. Pointers with Array using Programs. #pointerwitharray
16. Another Example of #pointerwitharray.
17. Relationship Between Arrays and Pointers.
18. Relationship Between Arrays and Pointers explanation with diagram.
19. Pointers and String. #PointersAndString
20. Function with Array Parameters using pointers.
21. Passing Pointers to Function or Pointer argument function. #PointerWithFunction
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 Presentation gives you all knowledge about #CPointers, #PointersInC.
The given slides are as follows:
1. Introduction of Pointers.
2. Systems to create a pointer in C.
3. Valid Pointer Examples in C.
4. Graphical representation of address assigning in c using pointer.
5. 1st Sample program of pointers in C.
6. Types of Pointers
7. NULL Pointer in C (Types of Pointer)
8. void Pointer in C (Types of Pointer)
9. Wild Pointer in C (Types of Pointer)
10. Changing value of variable using pointer
11. Update and Access value of variable using pointer in example.
12. Types of format specifies to print address in different format.
13. Advantages of Pointer in C.
14. Disadvantages of Pointer in C.
15. Pointers with Array using Programs. #pointerwitharray
16. Another Example of #pointerwitharray.
17. Relationship Between Arrays and Pointers.
18. Relationship Between Arrays and Pointers explanation with diagram.
19. Pointers and String. #PointersAndString
20. Function with Array Parameters using pointers.
21. Passing Pointers to Function or Pointer argument function. #PointerWithFunction
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.
An introduction to pointers and references in C++ (with elements of C++11 and C++14). The presentation introduces the readers to the concepts of pointers and references through the pragmatic need of writing a swap function between integers. Generic programming notions (e.g., type constructors) are adopted when useful for the explanation.
Pointers are among C’s most powerful, yet most difficult concepts to master. Some tasks like dynamic memory allocation done only by using pointers. So it is essential to learn pointers.
Pointers are a type of variable, just like int, double, etc., except instead of storing a value, they store a memory address of another variable.
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.
An introduction to pointers and references in C++ (with elements of C++11 and C++14). The presentation introduces the readers to the concepts of pointers and references through the pragmatic need of writing a swap function between integers. Generic programming notions (e.g., type constructors) are adopted when useful for the explanation.
Pointers are among C’s most powerful, yet most difficult concepts to master. Some tasks like dynamic memory allocation done only by using pointers. So it is essential to learn pointers.
Pointers are a type of variable, just like int, double, etc., except instead of storing a value, they store a memory address of another variable.
Content of slide
Tree
Binary tree Implementation
Binary Search Tree
BST Operations
Traversal
Insertion
Deletion
Types of BST
Complexity in BST
Applications of BST
Cyber security refers to every aspect of protecting an organization and its employees and assets against cyber threats. As cyberattacks become more common and sophisticated and corporate networks grow more complex, a variety of cyber security solutions are required to mitigate corporate cyber risk.
03 of 03 parts
Get Part 1 from https://www.slideshare.net/ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-1
Get Part 2 from https://www.slideshare.net/ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-2
C is a general-purpose, procedural computer programming language supporting structured programming, lexical variable scope, and recursion, while a static type system prevents unintended operations. C provides constructs that map efficiently to typical machine instructions and has found lasting use in applications previously coded in assembly language. Such applications include operating systems and various application software for computers, from supercomputers to PLCs and embedded system.
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...ssuserd6b1fd
C programming language notes for beginners and Collage students. Written for beginners. Colored graphics. Function by Function explanation with complete examples. Well commented examples. Illustrations are made available for data dealing at memory level.
Let's dive deeper into the world of ODC! Ricardo Alves (OutSystems) will join us to tell all about the new Data Fabric. After that, Sezen de Bruijn (OutSystems) will get into the details on how to best design a sturdy architecture within ODC.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
The field of Information retrieval (IR) is currently undergoing a transformative shift, at least partly due to the emerging applications of generative AI to information access. In this talk, we will deliberate on the sociotechnical implications of generative AI for information access. We will argue that there is both a critical necessity and an exciting opportunity for the IR community to re-center our research agendas on societal needs while dismantling the artificial separation between the work on fairness, accountability, transparency, and ethics in IR and the rest of IR research. Instead of adopting a reactionary strategy of trying to mitigate potential social harms from emerging technologies, the community should aim to proactively set the research agenda for the kinds of systems we should build inspired by diverse explicitly stated sociotechnical imaginaries. The sociotechnical imaginaries that underpin the design and development of information access technologies needs to be explicitly articulated, and we need to develop theories of change in context of these diverse perspectives. Our guiding future imaginaries must be informed by other academic fields, such as democratic theory and critical theory, and should be co-developed with social science scholars, legal scholars, civil rights and social justice activists, and artists, among others.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
I have heard many times that architecture is not important for the front-end. Also, many times I have seen how developers implement features on the front-end just following the standard rules for a framework and think that this is enough to successfully launch the project, and then the project fails. How to prevent this and what approach to choose? I have launched dozens of complex projects and during the talk we will analyze which approaches have worked for me and which have not.
"Impact of front-end architecture on development cost", Viktor Turskyi
pointers
1. Outline
7.1 Introduction
7.2 Pointer Variable Declarations and Initialization
7.3 Pointer Operators
7.4 Calling Functions by Reference
7.5 Using the Const Qualifier with Pointers
7.6 Bubble Sort Using Call by Reference
7.7 Pointer Expressions and Pointer Arithmetic
7.8 The Relationship between Pointers and Arrays
7.9 Arrays of Pointers
7.10 Case Study: A Card Shuffling and Dealing
Simulation
7.11 Pointers to Functions
2. Pointers
◦ Powerful, but difficult to master
◦ Simulate call-by-reference
◦ Close relationship with arrays and strings
3. Pointer variables
◦ Contain memory addresses as their values
◦ Normal variables contain a specific value (direct
reference)
◦ Pointers contain address of a variable that has a
specific value (indirect reference)
◦ Indirection - referencing a pointer value
count
7
countPtr
count
7
4. Pointer declarations
◦ * used with pointer variables
int *myPtr;
◦ Declares a pointer to an int (pointer of type int *)
◦ Multiple pointers, multiple *
int *myPtr1, *myPtr2;
◦ Can declare pointers to any data type
◦ Initialize pointers to 0, NULL, or an address
0 or NULL - points to nothing (NULL preferred)
5. & (address operator)
◦ Returns address of operand
int y = 5;
int *yPtr;
yPtr = &y; //yPtr gets address of y
◦ yPtr “points to” y
yPtr
y
5
yptr
500000 600000
y
600000 5
Address of y
is value of
yptr
6. * (indirection/dereferencing operator)
◦ Returns a synonym/alias of what its operand points to
*yptr returns y (because yptr points to y)
◦ * can be used for assignment
Returns alias to an object
*yptr = 7; // changes y to 7
◦ Dereferenced pointer (operand of *) must be an lvalue
(no constants)
7. * and & are inverses
◦ They cancel each other out
*&yptr -> * (&yptr) -> * (address of yptr)->
returns alias of what operand points to -> yptr
&*yptr -> &(*yptr) -> &(y) -> returns address of y,
which is yptr -> yptr
8. 1. Declare variables
2 Initialize variables
3. Print
Program Output
1 /* Fig. 7.4: fig07_04.c
2 Using the & and * operators */
3 #include <stdio.h>
4
5 int main()
6 {
7 int a; /* a is an integer */
8 int *aPtr; /* aPtr is a pointer to an integer */
9
10 a = 7;
11 aPtr = &a; /* aPtr set to address of a */
12
13 printf( "The address of a is %p"
14 "nThe value of aPtr is %p", &a, aPtr );
15
16 printf( "nnThe value of a is %d"
17 "nThe value of *aPtr is %d", a, *aPtr );
18
19 printf( "nnShowing that * and & are inverses of "
20 "each other.n&*aPtr = %p"
21 "n*&aPtr = %pn", &*aPtr, *&aPtr );
22
23 return 0;
24 }
The address of a is 0012FF88
The value of aPtr is 0012FF88
The value of a is 7
The value of *aPtr is 7
Proving that * and & are complements of each other.
&*aPtr = 0012FF88
*&aPtr = 0012FF88
The address of a is the value
of aPtr.
The * operator returns an
alias to what its operand
points to. aPtr points to a,
so *aPtr returns a.
Notice how * and
& are inverses
9. Call by reference with pointer arguments
◦ Pass address of argument using & operator
◦ Allows you to change actual location in memory
◦ Arrays are not passed with & because the array name is already
a pointer
* operator
◦ Used as alias/nickname for variable inside of function
void double(int *number)
{
*number = 2 * (*number);
}
*number used as nickname for the variable passed
10. 1. Function prototype
- takes a pointer to an
int.
1.1 Initialize variables
2. Call function
3. Define function
Program Output
1 /* Fig. 7.7: fig07_07.c
2 Cube a variable using call-by-reference
3 with a pointer argument */
4
5 #include <stdio.h>
6
7 void cubeByReference( int * ); /* prototype */
8
9 int main()
10 {
11 int number = 5;
12
13 printf( "The original value of number is %d", number );
14 cubeByReference( &number );
15 printf( "nThe new value of number is %dn", number );
16
17 return 0;
18 }
19
20 void cubeByReference( int *nPtr )
21 {
22 *nPtr = *nPtr * *nPtr * *nPtr; /* cube number in main */
23 }
The original value of number is 5
The new value of number is 125
Notice how the address of
number is given -
cubeByReference expects a
pointer (an address of a variable).
Inside cubeByReference,
*nPtr is used (*nPtr is
number).
11. const qualifier - variable cannot be changed
◦ Good idea to have const if function does not need to change a
variable
◦ Attempting to change a const is a compiler error
const pointers - point to same memory location
◦ Must be initialized when declared
int *const myPtr = &x;
Type int *const - constant pointer to an int
const int *myPtr = &x;
Regular pointer to a const int
const int *const Ptr = &x;
const pointer to a const int
x can be changed, but not *Ptr
12. 1. Declare variables
1.1 Declare const
pointer to an int.
2. Change *ptr
(which is x).
2.1 Attempt to change
ptr.
3. Output
Program Output
1 /* Fig. 7.13: fig07_13.c
2 Attempting to modify a constant pointer to
3 non-constant data */
4
5 #include <stdio.h>
6
7 int main()
8 {
9 int x, y;
10
11 int * const ptr = &x; /* ptr is a constant pointer to an
12 integer. An integer can be modified
13 through ptr, but ptr always points
14 to the same memory location. */
15 *ptr = 7;
16 ptr = &y;
17
18 return 0;
19 }
FIG07_13.c:
Error E2024 FIG07_13.c 16: Cannot modify a const object in
function main
*** 1 errors in Compile ***
Changing *ptr is allowed - x is
not a constant.
Changing ptr is an error -
ptr is a constant pointer.
13. Implement bubblesort using pointers
◦ Swap two elements
◦ swap function must receive address (using &) of array elements
Array elements have call-by-value default
◦ Using pointers and the * operator, swap can switch array elements
Psuedocode
Initialize array
print data in original order
Call function bubblesort
print sorted array
Define bubblesort
14. sizeof
◦ Returns size of operand in bytes
◦ For arrays: size of 1 element * number of elements
◦ if sizeof(int) = 4 bytes, then
int myArray[10];
printf( "%d", sizeof( myArray ) );
will print 40
sizeof can be used with
◦ Variable names
◦ Type name
◦ Constant values
15. 1. Initialize array
1.1 Declare variables
2. Print array
2.1 Call bubbleSort
2.2 Print array
1 /* Fig. 7.15: fig07_15.c
2 This program puts values into an array, sorts the values into
3 ascending order, and prints the resulting array. */
4 #include <stdio.h>
5 #define SIZE 10
6 void bubbleSort( int *, const int );
7
8 int main()
9 {
10
11 int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
12 int i;
13
14 printf( "Data items in original ordern" );
15
16 for ( i = 0; i < SIZE; i++ )
17 printf( "%4d", a[ i ] );
18
19 bubbleSort( a, SIZE ); /* sort the array */
20 printf( "nData items in ascending ordern" );
21
22 for ( i = 0; i < SIZE; i++ )
23 printf( "%4d", a[ i ] );
24
25 printf( "n" );
26
27 return 0;
28 }
29
30 void bubbleSort( int *array, const int size )
31 {
32 void swap( int *, int * );
Bubblesort gets passed the
address of array elements
(pointers). The name of an
array is a pointer.
16. 3. Function definitions
Program Output
33 int pass, j;
34 for ( pass = 0; pass < size - 1; pass++ )
35
36 for ( j = 0; j < size - 1; j++ )
37
38 if ( array[ j ] > array[ j + 1 ] )
39 swap( &array[ j ], &array[ j + 1 ] );
40 }
41
42 void swap( int *element1Ptr, int *element2Ptr )
43 {
44 int hold = *element1Ptr;
45 *element1Ptr = *element2Ptr;
46 *element2Ptr = hold;
47 }
Data items in original order
2 6 4 8 10 12 89 68 45 37
Data items in ascending order
2 4 6 8 10 12 37 45
17. Arithmetic operations can be performed on
pointers
◦ Increment/decrement pointer (++ or --)
◦ Add an integer to a pointer( + or += , - or -=)
◦ Pointers may be subtracted from each other
◦ Operations meaningless unless performed on an
array
18. 5 element int array on machine with 4 byte ints
◦ vPtr points to first element v[0]
at location 3000. (vPtr = 3000)
◦ vPtr +=2; sets vPtr to 3008
vPtr points to v[2] (incremented
by 2), but machine has 4 byte ints.
pointer variable vPtr
v[0] v[1] v[2] v[4]v[3]
3000 3004 3008 3012 3016
location
19. Subtracting pointers
◦ Returns number of elements from one to the other.
vPtr2 = v[2];
vPtr = v[0];
vPtr2 - vPtr == 2.
Pointer comparison ( <, == , > )
◦ See which pointer points to the higher numbered
array element
◦ Also, see if a pointer points to 0
20. Pointers of the same type can be assigned to
each other
◦ If not the same type, a cast operator must be used
◦ Exception: pointer to void (type void *)
Generic pointer, represents any type
No casting needed to convert a pointer to void pointer
void pointers cannot be dereferenced
21. Arrays and pointers closely related
◦ Array name like a constant pointer
◦ Pointers can do array subscripting operations
Declare an array b[5] and a pointer bPtr
bPtr = b;
Array name actually a address of first element
OR
bPtr = &b[0]
Explicitly assign bPtr to address of first element
22. Element b[n]
◦ can be accessed by *( bPtr + n )
◦ n - offset (pointer/offset notation)
◦ Array itself can use pointer arithmetic.
b[3] same as *(b + 3)
◦ Pointers can be subscripted (pointer/subscript
notation)
bPtr[3] same as b[3]
23. Arrays can contain pointers - array of strings
char *suit[4] = {"Hearts", "Diamonds", "Clubs", "Spades" };
◦ String: pointer to first character
◦ char * - each element of suit is a pointer to a char
◦ Strings not actually in array - only pointers to string in array
suit array has a fixed size, but strings can be of any
size.
suit[3]
suit[2]
suit[1]
suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’0’
’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’0’
’C’ ’l’ ’u’ ’b’ ’s’ ’0’
’S’ ’p’ ’a’ ’d’ ’e’ ’s’ ’0’
24. Card shuffling program
◦ Use array of pointers to strings
◦ Use double scripted array (suit, face)
◦ The numbers 1-52 go into the array - this is the order they are
dealt
Hearts
Diamonds
Clubs
Spades
0
1
2
3
Ace Two Three Four Five Six Seven Eight Nine Ten Jack Queen King
0 1 2 3 4 5 6 7 8 9 10 11 12
deck[2][12] represents the King of Clubs
Clubs King
25. Pseudocode - Top level: Shuffle and deal 52
cards
Initialize the suit array
Initialize the face array
Initialize the deck array
Shuffle the deck
Deal 52 cards
For each of the 52 cards
Place card number in randomly
selected unoccupied slot of deck
For each of the 52 cards
Find card number in deck array
and print face and suit of card
Choose slot of deck randomly
While chosen slot of deck has been
previously chosen
Choose slot of deck randomly
Place card number in chosen slot of
deck
For each slot of the deck array
If slot contains card number
Print the face and suit of the
card
Second refinement
Third refinement
First refinement
27. 3. Define functions
33 do {
34 row = rand() % 4;
35 column = rand() % 13;
36 } while( wDeck[ row ][ column ] != 0 );
37
38 wDeck[ row ][ column ] = card;
39 }
40 }
41
42 void deal( const int wDeck[][ 13 ], const char *wFace[],
43 const char *wSuit[] )
44 {
45 int card, row, column;
46
47 for ( card = 1; card <= 52; card++ )
48
49 for ( row = 0; row <= 3; row++ )
50
51 for ( column = 0; column <= 12; column++ )
52
53 if ( wDeck[ row ][ column ] == card )
54 printf( "%5s of %-8s%c",
55 wFace[ column ], wSuit[ row ],
56 card % 2 == 0 ? 'n' : 't' );
57 }
The numbers 1-52 are
randomly placed into the
deck array.
Searches deck for the
card number, then prints
the face and suit.
28. Program Output
Six of Clubs Seven of Diamonds
Ace of Spades Ace of Diamonds
Ace of Hearts Queen of Diamonds
Queen of Clubs Seven of Hearts
Ten of Hearts Deuce of Clubs
Ten of Spades Three of Spades
Ten of Diamonds Four of Spades
Four of Diamonds Ten of Clubs
Six of Diamonds Six of Spades
Eight of Hearts Three of Diamonds
Nine of Hearts Three of Hearts
Deuce of Spades Six of Hearts
Five of Clubs Eight of Clubs
Deuce of Diamonds Eight of Spades
Five of Spades King of Clubs
King of Diamonds Jack of Spades
Deuce of Hearts Queen of Hearts
Ace of Clubs King of Spades
Three of Clubs King of Hearts
Nine of Clubs Nine of Spades
Four of Hearts Queen of Spades
Eight of Diamonds Nine of Diamonds
Jack of Diamonds Seven of Clubs
Five of Hearts Five of Diamonds
Four of Clubs Jack of Hearts
Jack of Clubs Seven of Spades
29. Pointer to function
◦ Contains address of function
◦ Similar to how array name is address of first element
◦ Function name is starting address of code that defines function
Function pointers can be
◦ Passed to functions
◦ Stored in arrays
◦ Assigned to other function pointers
30. Example: bubblesort
◦ Function bubble takes a function pointer
bubble calls this helper function
this determines ascending or descending sorting
◦ The argument in bubblesort for the function pointer:
bool ( *compare )( int, int )
tells bubblesort to expect a pointer to a function that takes two
ints and returns a bool.
◦ If the parentheses were left out:
bool *compare( int, int )
Declares a function that receives two integers and returns a pointer to
a bool
31. 1. Initialize array.
2. Prompt for
ascending or
descending sorting.
2.1 Put appropriate
function pointer into
bubblesort.
2.2 Call bubble.
3. Print results.
1 /* Fig. 7.26: fig07_26.c
2 Multipurpose sorting program using function pointers */
3 #include <stdio.h>
4 #define SIZE 10
5 void bubble( int [], const int, int (*)( int, int ) );
6 int ascending( int, int );
7 int descending( int, int );
8
9 int main()
10 {
11
12 int order,
13 counter,
14 a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
15
16 printf( "Enter 1 to sort in ascending order,n"
17 "Enter 2 to sort in descending order: " );
18 scanf( "%d", &order );
19 printf( "nData items in original ordern" );
20
21 for ( counter = 0; counter < SIZE; counter++ )
22 printf( "%5d", a[ counter ] );
23
24 if ( order == 1 ) {
25 bubble( a, SIZE, ascending );
26 printf( "nData items in ascending ordern" );
27 }
28 else {
29 bubble( a, SIZE, descending );
30 printf( "nData items in descending ordern" );
31 }
32
Notice the function pointer
parameter.
32. 3.1 Define functions.
33 for ( counter = 0; counter < SIZE; counter++ )
34 printf( "%5d", a[ counter ] );
35
36 printf( "n" );
37
38 return 0;
39 }
40
41 void bubble( int work[], const int size,
42 int (*compare)( int, int ) )
43 {
44 int pass, count;
45
46 void swap( int *, int * );
47
48 for ( pass = 1; pass < size; pass++ )
49
50 for ( count = 0; count < size - 1; count++ )
51
52 if ( (*compare)( work[ count ], work[ count + 1 ] ) )
53 swap( &work[ count ], &work[ count + 1 ] );
54 }
55
56 void swap( int *element1Ptr, int *element2Ptr )
57 {
58 int temp;
59
60 temp = *element1Ptr;
61 *element1Ptr = *element2Ptr;
62 *element2Ptr = temp;
63 }
64
ascending and descending
return true or false.
bubble calls swap if the
function call returns true.
Notice how function pointers
are called using the
dereferencing operator. The *
is not required, but emphasizes
that compare is a function
pointer and not a function.
33. 3.1 Define functions.
Program Output
65 int ascending( int a, int b )
66 {
67 return b < a; /* swap if b is less than a */
68 }
69
70 int descending( int a, int b )
71 {
72 return b > a; /* swap if b is greater than a */
73 }
Enter 1 to sort in ascending order,
Enter 2 to sort in descending order: 1
Data items in original order
2 6 4 8 10 12 89 68 45 37
Data items in ascending order
2 4 6 8 10 12 37 45 68 89
Enter 1 to sort in ascending order,
Enter 2 to sort in descending order: 2
Data items in original order
2 6 4 8 10 12 89 68 45 37
Data items in descending order
89 68 45 37 12 10 8 6 4 2