[PDF] Pointers in C Dynamic memory allocation: Pointers make





Previous PDF Next PDF



w13-14-pointers-in-c.pdf

Dynamic memory allocation: Pointers make it possible to reserve new memory during program execution. Page 18. • Pointer variables. – Contain memory addresses as 



A TUTORIAL ON POINTERS AND ARRAYS IN C by Ted Jensen

After numerous requests I've finally come out with this PDF version which is identical One of those things beginners in C find difficult is the concept of ...



Understanding and Using C Pointers Understanding and Using C Pointers

This pointer assists in accessing the stack frame's elements. Neither of these pointers are C pointers. They are addresses used by the runtime system to 





C Programming for Engineers Pointers C Programming for Engineers Pointers

➢ Arrays and pointers are intimately related in C and often may be used interchangeably. ➢ An array name can be thought of as a constant pointer.



Pointers in C Programming with examples

Unlike other variables that hold values of a certain type pointer holds the address of a variable. For example



Pointers Pointers

Pointers. • A pointer is just a C variable whose value is the address of another variable! • After declaring a pointer: int *ptr; ptr doesn't actually point 



UNIT II FUNCTIONS AND POINTERS • Functions are created when

int x; *p; p = &x;. Page 16. Sri vidya college of engineering and technology course material. EC 8393/Fundamentals of data structures in C unit 2. This is 



Hazard Pointers for C++26

2 мар. 2023 г. We propose the hazard pointer safe deferred reclamation technique [1] for inclusion in C++26. This paper contains proposed interface and ...



UNIT – V CHAPTER XI POINTERS

In C we use pointer as a reference. (vi) Storage of strings through pointers saves memory space. (vii) Pointers may be used to pass on arrays



A TUTORIAL ON POINTERS AND ARRAYS IN C by Ted Jensen

After numerous requests I've finally come out with this PDF version which is identical In C when we define a pointer variable we do so by preceding its.



Pointers in C

Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily with pointers and other tasks



C Programming for Engineers Pointers

Arrays and pointers are intimately related in C and often may be used interchangeably. ? An array name can be thought of as a constant pointer.



Understanding and Using C Pointers

Media Inc. Understanding and Using C Pointers



Pointers in C

Dynamic memory allocation: Pointers make it possible to reserve new memory during program execution. Page 18. • Pointer variables. – Contain memory addresses as 



Pointers

Dept. of CSE IIT KGP. Pointers. • A pointer is just a C variable whose value is the address of another variable! • After declaring a pointer: int *ptr;.



C Arrays Strings

https://inst.eecs.berkeley.edu/~cs61c/resources/su18_lec/Lecture3.pdf



C Pointers and Arrays

Pointers and Arrays. We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer. Address of a variable in memory.



Testing Inexecutable Conditions on Input Pointers in C Programs

bounds memory access in C programs and to confirm it on concrete test data. However this is not directly possible for input arrays/pointers in C functions.



Using C++11s Smart Pointers - David Kieras EECS Department

This tutorial deals with C++11's smart pointer facility which consists unique_ptr



A TUTORIAL ON POINTERS AND ARRAYS IN C

A TUTORIAL ON POINTERS AND ARRAYS IN C by Ted Jensen Version 1 2 (PDF Version) Sept 2003 This material is hereby placed in the public domain Available in various formats via http://pweb netcom com/~tjensen/ptr/cpoint htm TABLE OF CONTENTS PREFACE 2 INTRODUCTION 4 CHAPTER 1: What is a pointer?



Pointers and Memory - Stanford University

Pointers and Memory By Nick ParlanteCopyright ©1998-2000 Nick Parlante Abstract This document explains how pointers and memory work and how to use them—from the basic concepts through all the major programming techniques For each topic there is a combination of discussion sample C code and drawings



Understand use of Pointers (*) in C and C++

Pointers may be assigned and compared for equality using the usual operators Pointers may also be manipulated by incrementing and decrementing although doing so is only safe under precisely-defined circumstances By convention pointers without targets should be set to 0 (or NULL)



Lecture 5 Notes: Pointers 1 Background - MIT OpenCourseWare

2 2 1 Declaring Pointers To declare a pointer variable named ptr that points to an integer variable named x: int *ptr = &x; int *ptr declares the pointer to an integer value which we are initializing to the address of x We can have pointers to values of any type The general scheme for declaring pointers is:



Pointers in C - IIT Kharagpur

A pointer is a variable that represents the location (rather than the value) of a data item They have a number of useful applications Enables us to access a variable that is defined outside the function Can be used to pass information back and forth between a function and its reference point More efficient in handling data tables



Searches related to pointers in c pdf filetype:pdf

pointer is an address in the memory One of the unique advantages of using C is that it provides direct access to a memory location through its address A variable declared as int x has the address given by &x & is a unary operator that allows the programmer to access the address of a single variable declared

What is a pointer in C and C++?

    A pointer in C and C++ is a variable that contains a memory address which is usually the address/ location of another variable in the memory. So, for example, if I say the pointer variable 'ptr' points to variable x, I mean that 'ptr' holds the memory location or the exact address where x is stored in the memory.

How to pointer to an int variable in C?

    A pointer or address variable to an int is defined as: int* ptr; The * can be placed anywhere between int and ptr. Compiler will consider ptr to be an address of a variable of int type. Therefore any dereferencing of the ptr variable will cause the program to look for 4 bytes of memory.

What is the memory size of a pointer in C?

    The memory size of a C pointer for a 16-bit system is 2 bytes. We must understand the use of two operators (& and *) for using pointers in C. The unary operator, &, is used for getting the address of the variable. If you use '&' before a variable name, it returns the address of that variable.

What is a pointer in Java?

    What are Pointers? 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 using it to store any variable address. The general form of a pointer variable declaration is ?

Recap:AnatomyofaTypicalCProgram#preprocessor directivesdeclarationsvariablesfunctionsintmain(void){declarations;statements;returnvalue;}

/* Welcome to BBM 101 */#include intmain(void){printf("Hello world!\n");return 0;}Hello world!hello.cYourFirstCProgram

YourFirstCProgram/* Welcome to BBM 101 */#include intmain(void){printf("Hello world!\n");return 0;}Hello world!/*comments*/globaldeclarations#includeexternalfilesmainfunctionhello.c

/* Welcome to BBM 101 */#include intmain(void){printf("Hello world!\n");return 0;}Hello world!/*comments*/globaldeclarations#includeexternalfilesmainfunctionhello.cTextsurroundedby/*and*/isignoredbycomputerYourFirstCProgram

/* Welcome to BBM 101 */#include intmain(void){printf("Hello world!\n");return 0;}Hello world!/*comments*/globaldeclarations#includeexternalfilesmainfunctionhello.c"stdio.h"allowsstandardinput/outputoperationsYourFirstCProgram

/* Welcome to BBM 101 */#include intmain(void){printf("Hello world!\n");return 0;}Hello world!/*comments*/globaldeclarations#includeexternalfilesmainfunctionhello.cCprogramscontainoneormorefunctions,exactlyoneofwhichmustbemainYourFirstCProgram

Themain(void)ofhello.cintmain(void){printf("Hello world!\n");return 0;}Programintmain(void)ArgumentsReturnvalue•Noarguments.•Returnsanintegervariable.return"0"toOS:"everythingisOK"Slidecredit:BertHuang

CStatements•One-linecommands•Alwaysendinsemicolon;•Examples:-callfunction:printf("hello"); /* from stdio*/-declarevariable:intx;-assignvariablevalue:x = 123+456;

VariablesRevisited•Whatactuallyhappenswhenwedeclarevariables?char a;•Creservesabyteinmemorytostorea.•Whereisthatmemory?Atanaddress.•Underthehood,Chasbeenkeepingtrackofvariablesandtheiraddresses.Slidecredit:B.Huang

•Pointerdeclarations-Thesyntaxforpointerdeclarationisasfollows:type*identifier;e.g.int*myPtr;-Declaresapointertoanint(pointeroftypeint*)-Multiplepointersrequireusinga*beforeeachvariabledeclarationint*myPtr1, *myPtr2;-Candeclarepointerstoanydatatype-Initializepointersto0, NULL, oranaddress•0orNULL-pointstonothing(NULLpreferred)PointerVariableDeclarationsandInitialization

PointerOperators•&(addressoperator)-Returnstheaddressofoperandinty = 5;int*yPtr; yPtr= &y; // yPtrgets address of y-yPtr"pointsto"yyPtry5yptr500000600000y6000005Addressofyisvalueofyptr

PointerOperators•*(indirection/dereferencingoperator)-Returnsasynonym/aliasofwhatitsoperandpointsto-*yptrreturnsy(becauseyptrpointstoy)-*canbeusedforassignment•Returnsaliastoanobject*yptr= 7; // changes y to 7-Dereferencedpointer(operandof*)mustbeanlvalue(noconstants)•*and&areinverses-Theycanceleachotherout

intrate;int*p_rate;rate = 500;p_rate= &rate;10001004100810125001008ratep_rateMemory/* Print the values */printf("rate = %d\n", rate); /* direct access */printf("rate = %d\n", *p_rate); /* indirect access */

ProgramOutput/* Using the & and * operators */ #includeintmain(){inta; /* a is an integer */int*aPtr; /* aPtris a pointer to an integer */a = 7;aPtr= &a; /* aPtrset to address of a */printf( "The address of a is %p\nThe value of aPtr is %p", &a, aPtr );printf( "\n\nThe value of a is %d\nThe value of *aPtr is %d", a, *aPtr );printf( "\n\nShowing that * and & are inverses of each other.\n&*aPtr= %p\n*&aPtr= %p\n", &*aPtr, *&aPtr);return0;}The address of a is 0012FF88The value of aPtris 0012FF88The value of a is 7The value of *aPtris 7Showing that * and & are inverses of each other.&*aPtr= 0012FF88*&aPtr= 0012FF88TheaddressofaisthevalueofaPtr.The*operatorreturnsanaliastowhatitsoperandpointsto.aPtrpointstoa,so*aPtrreturnsa.Noticehow*and&areinverses

inta, b, *p;a = b = 7;p = &a;printf("*p = %d\n",*p);*p = 3;printf("a = %d\n",a);p = &b;*p = 2 * *p -a;printf("b = %d \n", b);AddressingandDereferencing*p = 7a = 3b = 11ProgramOutput

AddressingandDereferencingfloat x, y, *p;x = 5;y = 7;p = &x;y = *p;Thus,y = *p; y = *&x; y = x;Allequivalent

AddressingandDereferencingExpressionEquivalent0ExpressionValuep == &kp == (&k)1p = k + 7p = (k + 7)illegal* * &p* ( * (&p))3r = &xr = (& x)illegal7 * * p/ *q +7(( (7 * (*p) )) / (*q)) + 7 11* (r = &j) *= *p( * (r = (&j))) *= (*p)15double x;int k=3, j=5, *p = &k, *q = &j, *r;Declarations0and0initializations

Pointerstovoid•void *identifier;•InC,voidrepresentstheabsenceoftype.•voidpointersarepointersthatpointtoavaluethathasnospecifictype.•Thisallowsvoidpointerstopointtoanydatatype.•Thedatapointedbyvoidpointerscannotbedirectlydereferenced.•Wehavetouseexplicittypecastingbeforedereferencingit.

Legal&assignmentsIllegal&assignmentsp = 0;p = 1;p = (int *) 1;v = 1;p = v = q;p = q;p = (int *) q;int *p;float *q;void *v;Declarations

Pointerstovoidintx = 4;void *q = &x;int*p = q; inti= *p;intj = *(int*)q;

CallingFunctionsbyReference•Callbyreferencewithpointerarguments-Passaddressofargumentusing&operator-Allowsyoutochangeactuallocationinmemory-Arraysarenotpassedwith&becausethearraynameisalreadyapointer•*operator-Usedasalias/nicknameforvariableinsideoffunctionvoid double_it( int*number ){*number = 2 * ( *number );}-*numberusedasnicknameforthevariablepassed

Passingparametersbyreferencevoid SetToZero(intvar){var= 0;}•Youwouldmakethefollowingcall:SetToZero(x);•Thisfunctionhasnoeffectwhatever.Instead,passapointer:void SetToZero(int*ip){*ip= 0;}Youwouldmakethefollowingcall:SetToZero(&x);Thisisreferredtoascall-by-reference.

/* An example using call-by-reference */#includevoid change_arg(int*y);intmain (void){intx = 5;change_arg(&x);printf("%d \n", x);return 0;}void change_arg(int*y){*y = *y + 2;}

/* Cube a variable using call-by-referencewith a pointer argument */#includevoidcubeByReference( int* ); /* prototype */intmain(){intnumber = 5;printf( "The original value of number is %d", number );cubeByReference( &number );printf( "\nThe new value of number is %d\n", number );return0;}voidcubeByReference( int*nPtr ){*nPtr = *nPtr * *nPtr * *nPtr; /* cube number in main */}The original value of number is 5The new value of number is 125Noticehowtheaddressofnumberisgiven-cubeByReferenceexpectsapointer(anaddressofavariable).InsidecubeByReference,*nPtrisused(*nPtrisnumber).Noticethatthefunctionprototypetakesapointertoaninteger(int*).ProgramOutput

/* Cube a variable using call by value */#includeintCubeByValue(intn);intmain(void){intnumber = 5;printf("The original value of number is %d\n", number);number = CubeByValue(number);printf("The new value of number is %d\n",number);return 0;}intCubeByValue(intn){return (n*n*n);}

/* Swapping arguments (incorrect version) */#includevoid swap (intp, intq);intmain (void){inta = 3;intb = 7;printf("%d %d\n", a,b);swap(a,b);printf("%d %d\n", a, b);return 0;}void swap (intp, intq){inttmp;tmp= p;p = q;q = tmp;}

/* Swapping arguments (correct version) */#includevoid swap (int*p, int*q);intmain (void){inta = 3;intb = 7;printf("%d %d\n", a,b);swap(&a, &b);printf("%d %d\n", a, b);return 0;}void swap (int*p, int*q){inttmp;tmp= *p;*p= *q;*q= tmp;}3737pqpq

/** This function separates a number into three parts: a sign (+, -, * or blank), a whole number magnitude and a fraction part.* Preconditions: numis defined; signp, wholepand fracpcontain * addresses of memory cells where results are to be stored* Postconditions: function results are stored in cells pointed to by * signp, wholep, and fracp*/void separate(double num, char *signp, int*wholep, double *fracp){double magnitude;if (num< 0)*signp= '-';else if (num== 0)*signp= ' ';else *signp= '+';magnitude = fabs(num);*wholep= floor(magnitude);*fracp= magnitude -*wholep;}

intmain(){double value;char sn;intwhl;double fr;/* Gets data */printf("Enter a value to analyze:");scanf("%lf", &value);/* Separates data value in three parts */separate(value, &sn, &whl, &fr);/* Prints results */printf("Parts of %.4f\n sign: %c\n", value, sn);printf("whole number magnitude: %d\n", whl);printf("fractional part : %.4f\n", fr);return 0;}Enter a value to analyze:13.3Parts of 13.3000 sign: +whole number magnitude: 13fractional part : 0.3000Enter a value to analyze:-24.3Parts of -24.3000sign: -whole number magnitude: 24fractional part : 0.3000ProgramOutput

Example/* This program puts values into an array, sorts the values intoascending order, and prints the resulting array. */#include#defineSIZE 10voidbubbleSort( int*array, constintsize ); void swap( int*element1Ptr, int*element2Ptr ); intmain() {/* initialize array a */inta[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; inti; printf( "Data items in original order\n" );for ( i= 0; i< SIZE; i++ )printf( "%4d", a[ i] );bubbleSort( a, SIZE ); /* sort the array */printf( "\nDataitems in ascending order\n" );

Example/* loop through array a */for ( i= 0; i< SIZE; i++ )printf( "%4d", a[ i] ); printf( "\n" ); return 0; /* indicates successful termination */} /* end main *//* sort an array of integers using bubble sort algorithm */void bubbleSort( int*array, constintsize ){intpass,j; for ( pass = 0; pass < size -1; pass++ )for ( j = 0; j < size -1; j++ ) /* swap adjacent elements if they are out of order */ if ( array[ j ] > array[ j + 1 ] )swap( &array[ j ], &array[ j + 1 ] );} /* end function bubbleSort*/

Example/* swap values at memory locations to which element1Ptr andelement2Ptr point */ void swap( int*element1Ptr, int*element2Ptr ) { inthold = *element1Ptr; *element1Ptr = *element2Ptr; *element2Ptr = hold; } /* end function swap */ Data items in original order2 6 4 8 10 12 89 68 45 37Data items in ascending order2 4 6 8 10 12 37 45 68 89ProgramOutput

sizeof function•sizeof-Returnssizeofoperandinbytes-Forarrays:sizeof1element*numberofelements-ifsizeof( int)equals4bytes,thenintmyArray[ 10 ];printf( "%d", sizeof( myArray) );•willprint40•sizeofcanbeusedwith-Variablenames-Typename-Constantvalues

Example/* sizeofoperator when used on an array name returns the number of bytes in the array. */#include size_tgetSize( float *ptr); /* prototype */intmain(){float array[ 20 ];/* create array */printf( "The number of bytes in the array is %d" "\nThenumber of bytes returned by getSizeis %d\n",sizeof( array ), getSize( array ) ); return 0; } size_tgetSize( float *ptr) {return sizeof( ptr); }The number of bytes in the array is 80The number of bytes returned by getSizeis 4 ProgramOutput

Example/* Demonstrating the sizeofoperator */#includeintmain(){ char c; /* define c */shorts; /* define s */inti; /* define i*/longl; /* define l */floatf; /* define f */doubled; /* define d */long doubleld; /* define ld*/intarray[ 20 ]; /* initialize array */int*ptr= array; /* create pointer to array */

Exampleprintf( " sizeofc = %d\tsizeof(char) = %d" "\n sizeofs = %d\tsizeof(short) = %d" "\n sizeofi= %d\tsizeof(int) = %d" "\n sizeofl = %d\tsizeof(long) = %d" "\n sizeoff = %d\tsizeof(float) = %d" "\n sizeofd = %d\tsizeof(double) = %d" "\n sizeofld= %d\tsizeof(long double) = %d" "\n sizeofarray = %d" "\n sizeofptr= %d\n", sizeofc, sizeof( char ), sizeofs, sizeof( short ), sizeofi, sizeof( int), sizeofl, sizeof( long ), sizeoff, sizeof( float ), sizeofd, sizeof( double ),sizeofld, sizeof( long double ), sizeofarray, sizeofptr); return 0; }

Examplesizeofc = 1 sizeof(char) = 1sizeofs = 2 sizeof(short) = 2sizeofi= 4 sizeof(int) = 4sizeofl = 4 sizeof(long) = 4sizeoff = 4 sizeof(float) = 4sizeofd = 8 sizeof(double) = 8sizeofld= 8 sizeof(long double) = 8sizeofarray = 80sizeofptr= 4 ProgramOutput

DynamicMemoryManagement•Staticmemoryallocation:spacefortheobjectisprovidedinthebinaryatcompile-time•Dynamicmemoryallocation:blocksofmemoryofarbitrarysizecanberequestedatrun-time•Thefourdynamicmemorymanagementfunctionsaremalloc, calloc, realloc,andfree.•Thesefunctionsareincludedintheheaderfile.

DynamicMemoryManagement•void *malloc(size_tsize);•allocatesstorageforanobjectwhosesizeisspecifiedbysize:-Itreturnsapointertotheallocatedstorage,-NULLifitisnotpossibletoallocatethestoragerequested.-Theallocatedstorageisnotinitializedinanyway.•e.g.float *fp, fa[10];fp= (float *) malloc(sizeof(fa));allocatesthestoragetoholdanarrayof10floating-pointelements,andassignsthepointertothisstoragetofp.

DynamicMemoryManagement•void *calloc(size_tnobj, size_tsize);•allocatesthestorageforanarrayofnobjobjects,eachofsizesize.-Itreturnsapointertotheallocatedstorage,-NULLifitisnotpossibletoallocatethestoragerequested.-Theallocatedstorageisinitializedtozeros.•e.g.double *dp, da[10];dp=(double *) calloc(10,sizeof(double));allocatesthestoragetoholdanarrayof10doublevalues,andassignsthepointertothisstoragetodp.

DynamicMemoryManagement•void *realloc(void *p, size_tsize);•changesthesizeoftheobjectpointedtobyptosize.-Itreturnsapointertothenewstorage,-NULLifitisnotpossibletoresizetheobject,inwhichcasetheobject(*p) remainsunchanged.-Thenewsizemaybelarger(theoriginalcontentsarepreservedandtheremainingspaceisunitialized)orsmaller(thecontentsareunchangeduptothenewsize)thantheoriginalsize.

DynamicMemoryManagement•e.g.char *cp;cp=(char *) malloc(sizeof("computer"));strcpy(cp, "computer");cppointstoanarrayof9characterscontainingthenull-terminatedstringcomputer.cp= (char *) realloc(cp, sizeof("compute"));discardsthetrailing'\0'andmakescppointtoanarrayif8characterscontainingthecharactersincomputercp=(char *)realloc(cp,sizeof("computerization"));cppointstoanarrayof16characters,thefirst9ofwhichcontainthenull-terminatedstringcomputerandtheremaining7areuninitialized.

DynamicMemoryManagement•void *free(void *p);•deallocatesthestoragepointedtobyp,wherepisapointertothestoragepreviouslyallocatedbymalloc,calloc,orrealloc.•e.g.free(fp);free(dp);free(cp);

•5elementintarrayonmachinewith4byteints-vPtrpointstofirstelementv[0]•i.e.location3000(vPtr= 3000)-vPtr+= 2;sets vPtrto 3008•vPtrpointstov[2](incrementedby2),butthemachinehas4byteints,soitpointstoaddress3008pointer variable vPtrv[0]v[1]v[2]v[4]v[3]30003004300830123016locationPointerExpressionsandPointerArithmetic

•Subtractingpointers-Returnsnumberofelementsfromonetotheother.IfvPtr= &v[ 0 ];vPtr2 = &v[ 2 ]; //vPtr2 = vPtr+ 2;-vPtr2 -vPtrwouldproduce2•Pointercomparison(<,==,>)-Seewhichpointerpointstothehighernumberedarrayelement-Also,seeifapointerpointsto0PointerExpressionsandPointerArithmetic

PointerExpressionsandPointerArithmetic•Pointersofthesametypecanbeassignedtoeachother-Ifnotthesametype,acastoperatormustbeused-Exception:pointertovoid(typevoid *)•Genericpointer,representsanytype•Nocastingneededtoconvertapointertovoidpointer•voidpointerscannotbedereferenced

ExampleintSumIntegerArray(int*ip, intn){inti, sum;sum = 0;for (i=0; i< n; i++) {sum += *ip++;}return sum;}Assumeintsum, list[5];aredeclaredinthemainfunction.Wecanmakethefollowingfunctioncall:sum = SumIntegerArray(list, 5);

Example#include#includeintmain(void) {int*array, *p;inti,no_elements;printf("Enter number of elements: ");scanf("%d",&no_elements);printf("Enter the elements: ");array = ( int* )malloc( no_elements*sizeof( int) );for(p=array,i=0; i

Examplearray = ( int* )realloc(array, (no_elements+2)*sizeof( int) );printf("Enter two new elements: ");for(p=array,i=0; i

UsingtheconstQualifierwithPointers**•constqualifier-Variablecannotbechanged-Useconstiffunctiondoesnotneedtochangeavariable-Attemptingtochangeaconstvariableproducesanerror•constpointers-Pointtoaconstantmemorylocation-Mustbeinitializedwhendefined-int*constmyPtr= &x;•Typeint*const-constantpointertoanint-constint*myPtr= &x;•Regularpointertoaconstint-constint*constPtr= &x;•constpointertoaconstint•xcanbechanged,butnot*Ptr

Example/* Converting lowercase letters to uppercase letters using a non-constant pointer to non-constant data */#include#includevoid convertToUppercase( char *sPtr); intmain(){char string[] = "characters and $32.98"; /* initialize char array */printf( "The string before conversion is: %s", string );convertToUppercase( string );printf( "\nThestring after conversion is: %s\n", string ); return 0; /* indicates successful termination */}

Example/* convert string to uppercase letters */void convertToUppercase( char *sPtr){while ( *sPtr!= '\0') { if ( islower( *sPtr)) { /* if character is lowercase, */*sPtr= toupper( *sPtr);/* convert to uppercase */} ++sPtr;/* move sPtrto the next character */}} /* end function convertToUppercase*/The string before conversion is: characters and $32.98The string after conversion is: CHARACTERS AND $32.98 ProgramOutput

Example/* Printing a string one character at a time using a non-constant pointer to constant data */#includevoid printCharacters( constchar *sPtr);intmain(){/* initialize char array */char string[] = "print characters of a string"; printf( "The string is:\n" );printCharacters( string );printf( "\n" );return 0;}

Example/* sPtrcannot modify the character to which it points, i.e., sPtris a "read-only" pointer */void printCharacters( constchar *sPtr){/* loop through entire string */ for ( ; *sPtr!= '\0'; sPtr++ ) printf( "%c", *sPtr); } /* end function printCharacters*/The string is:print characters of a string ProgramOutput

Example/*Attempting to modify data through a non-constant pointer to constant data.*/#includevoid f( constint*xPtr); /* prototype */intmain(){inty; /* define y */ f( &y ); /* f attempts illegal modification */ return 0; /* indicates successful termination */ }/* end main *//* xPtrcannot be used to modify the value of the variable to which it points */void f( constint*xPtr){*xPtr= 100; /* error: cannot modify a constobject */}/* end functio */Syntax error: l-value specifies constobject

Example/* Attempting to modify a constant pointer to non-constant data */#includeintmain(){intx; /* define x */inty; /* define y *//* ptris a constant pointer to an integer that can be modified through ptr, but ptralways points to the same memory location */int* constptr= &x; *ptr= 7; /* allowed: *ptris not const*/ptr= &y; /* error: ptris const; cannot assign new address */return 0;} /* end main */Changing*ptrisallowed-xisnotaconstant.Changingptrisanerror-ptrisaconstantpointer.Syntax error: l-value specifies constobject

Example/* Attempting to modify a constant pointer to constant data. */#includeintmain() {intx = 5; /* initialize x */inty; /* define y *//* ptris a constant pointer to a constant integer. ptralways points to the same location; the integer at that location cannot be modified */constint*constptr= &x; printf( "%d\n", *ptr);*ptr= 7; /* error: *ptris const; cannot assign new value */ ptr= &y; /* error: ptris const; cannot assign new address */return 0; /* indicates successful termination */} /* end main */Syntax error: assignment of read-only locationsyntax error: assignment of read-only variable 'ptr'

PointersandArrays•Arraysareimplementedaspointers.•Consider:double list[3];&list[1]:istheaddressofthesecondelement&list[i]:theaddressoflist[i]whichiscalculatedbytheformulabaseaddressofthearray+i*8

•Arraysandpointersarecloselyrelated-Arraynameislikeaconstantpointer-Pointerscandoarraysubscriptingoperations•Declareanarrayb[5]andapointerbPtr-Tosetthemequaltooneanotheruse:bPtr= b; •Thearrayname(b)isactuallytheaddressoffirstelementofthearrayb[5]bPtr= &b[0] •ExplicitlyassignsbPtrtoaddressoffirstelementofbTheRelationshipbetweenPointersandArrays

-Elementb[3] •Canbeaccessedby*(bPtr+3)-Wherenistheoffset.Calledpointer/offsetnotation•Canbeaccessedbybptr[3]-Calledpointer/subscriptnotation-bPtr[3]sameasb[3]•Canbeaccessedbyperformingpointerarithmeticonthearrayitself*(b+3)TheRelationshipbetweenPointersandArrays

Example(cont.)/* Using subscripting and pointer notations with arrays */#includeintmain(void){inti, offset, b[4]={10,20,30,40};int*bPtr= b;/* Array is printed with array subscript notation */for (i=0; i< 4; i++)printf("b[%d] = %d\n", i, b[i]);

Example(cont.)/* Pointer/offset notation where the pointer is the array name */for (offset=0; offset < 4; offset++)printf("*(b + %d) = %d\n",offset,*(b + offset)); /* Pointer subscript notation */for (i=0; i< 4; i++)printf("bPtr[%d] = %d\n", i, bPtr[i]);/* Pointer offset notation */for (offset = 0; offset < 4; offset++)printf("*(bPtr+ %d) = %d\n", offset""*(bPtr+ offset)");return 0;}

Example(cont.)b[ 0 ] = 10b[ 1 ] = 20b[ 2 ] = 30b[ 3 ] = 40*( b + 0 ) = 10*( b + 1 ) = 20*( b + 2 ) = 30*( b + 3 ) = 40bPtr[ 0 ] = 10bPtr[ 1 ] = 20bPtr[ 2 ] = 30bPtr[ 3 ] = 40*( bPtr+ 0 ) = 10*( bPtr+ 1 ) = 20*( bPtr+ 2 ) = 30*( bPtr+ 3 ) = 40

Example/* Copying a string using array notation and pointer notation. */#includevoid copy1( char *s1, constchar *s2 ); void copy2( char *s1, constchar *s2 ); intmain(){char string1[ 10 ]; /* create array string1 */char*string2 = "Hello"; /* create a pointer to a string */charstring3[ 10 ]; /* create array string3 */charstring4[] = "Good Bye"; /* create a pointer to a string */copy1( string1, string2 );printf( "string1 = %s\n", string1 );copy2( string3, string4 );printf( "string3 = %s\n", string3 );return0; }

Example/* copy s2 to s1 using array notation */void copy1( char *s1, constchar *s2 ){inti; for ( i= 0; ( s1[ i] = s2[ i] ) != '\0'; i++ ); } /* end function copy1 *//* copy s2 to s1 using pointer notation */void copy2( char *s1, constchar *s2 ){/* loop through strings */for ( ; ( *s1 = *s2 ) != '\0'; s1++, s2++ ); } /* end function copy2 */string1 = Hellostring3 = Good ByeProgramOutput

ArraysofPointers•Arrayscancontainpointers•Forexample:anarrayofstringschar *suit[ 4 ] = { "Hearts", "Diamonds","Clubs", "Spades" };-Stringsarepointerstothefirstcharacter-char *-eachelementofsuitisapointertoachar-Thestringsarenotactuallystoredinthearraysuit,onlypointerstothestringsarestored-suitarrayhasafixedsize,butstringscanbeofanysizesuit[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'

PointerstoFunctions•Example:bubblesort-Functionbubbletakesafunctionpointer•bubblecallsthishelperfunction•thisdeterminesascendingordescendingsorting-Theargumentinbubblesortforthefunctionpointer:int( *compare )( inta, intb )tellsbubblesorttoexpectapointertoafunctionthattakestwointsandreturnsanint-Iftheparentheseswereleftout:int*compare( inta, intb )•Definesafunctionthatreceivestwointegersandreturnsapointertoaint

Example/* Multipurpose sorting program using function pointers */#include#defineSIZE 10void bubble( intwork[], constintsize, int(*compare)( inta, intb ));intascending( inta, intb );intdescending( inta, intb );intmain() {intorder; /* 1 for ascending order or 2 for descending order */intcounter; /* counter *//* initialize array a */inta[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };printf( "Enter 1 to sort in ascending order,\n" "Enter 2 to sort in descending order: " );scanf( "%d", &order ); printf( "\nDataitems in original order\n" );

Example/* output original array */for ( counter = 0; counter < SIZE; counter++ ) printf( "%5d", a[ counter ] ); /* sort array in ascending order; pass function ascending as an argument */if ( order == 1 ) {bubble( a, SIZE, ascending );printf( "\nDataitems in ascending order\n" ); } else { /* pass function descending */bubble( a, SIZE, descending );printf( "\nDataitems in descending order\n" ); } /* output sorted array */for ( counter = 0; counter < SIZE; counter++ ) printf( "%5d", a[ counter ] ); printf( "\n" );return 0; }

Example/* multipurpose bubble sort; parameter compare is a pointer tothe comparison function that determines sorting order */void bubble( intwork[], constintsize, int(*compare)( inta, intb )){intpass; /* pass counter */intcount; /* comparison counter */void swap( int*element1Ptr, int*element2ptr ); for ( pass = 1; pass < size; pass++ ) {for ( count = 0; count < size -1; count++ ) { /* if adjacent elements are out of order, swap them */if ( (*compare)( work[ count ], work[ count + 1 ] )) {swap( &work[ count ], &work[ count + 1 ] );} } } }/* end function bubble */

Example/*swap values at memory locations to which element1Ptr and element2Ptr point */void swap( int*element1Ptr, int*element2Ptr ){inthold; /* temporary holding variable */hold = *element1Ptr;*element1Ptr = *element2Ptr;*element2Ptr = hold;} /* end function swap *//* determine whether elements are out of order for an ascending order sort */ intascending( inta, intb ) { return b < a; } /* end function ascending */ /* determine whether elements are out of order for a descending order sort */ intdescending( inta, intb ) { return b > a; /* swap if b is greater than a */ } /* end function descending */

ExampleEnter 1 to sort in ascending order,Enter 2 to sort in descending order: 2Data items in original order2 6 4 8 10 12 89 68 45 37Data items in descending order89 68 45 37 12 10 8 6 4 2Enter 1 to sort in ascending order,Enter 2 to sort in descending order: 2Data items in original order2 6 4 8 10 12 89 68 45 37Data items in descending order89 68 45 37 12 10 8 6 4 2ProgramOutput

quotesdbs_dbs22.pdfusesText_28
[PDF] pointers in embedded c pdf

[PDF] points d'inflexion anglais

[PDF] points of the treaty of versailles

[PDF] pokemon ruby guide book

[PDF] pokemon ruby guide book pdf

[PDF] poland schengen visa appointment dublin

[PDF] pole barn kits

[PDF] pole barn plans

[PDF] pole barn prices

[PDF] police and private security partnerships

[PDF] police api

[PDF] police application form examples

[PDF] police application process

[PDF] police authority and power

[PDF] police body search procedures