<< Chapter < Page Chapter >> Page >

here is the sample session with the above program

Enter the number of elements: : 5 Enter the value of m[0]: 34 Enter the value of m[1]: 20 Enter the value of m[2]: 17 Enter the value of m[3]: 65 Enter the value of m[4]: 21 The array before sorting: 34 20 17 65 21The array after step 1: 17 34 20 65 21 The array after step 2: 17 20 34 65 21The array after step 3: 17 20 21 65 34 The array after step 4: 17 20 21 34 65

Pointers vs arrays

Pointers occur in many C programs as references to arrays , and also as elements of arrays. A pointer to an array type is called an array pointer for short, and an array whose elements are pointers is called a pointer array.

Array pointers

For the sake of example, the following description deals with an array of int. The same principles apply for any other array type, including multidimensional arrays.

To declare a pointer to an array type, you must use parentheses, as the following example illustrates:

int (* arrPtr)[10] = NULL; // A pointer to an array of// ten elements with type int.

Without the parentheses, the declaration int * arrPtr[10]; would define arrPtr as an array of 10 pointers to int. Arrays of pointers are described in the next section.

In the example, the pointer to an array of 10 int elements is initialized with NULL. However, if we assign it the address of an appropriate array, then the expression *arrPtr yields the array, and (*arrPtr)[i] yields the array element with the index i. According to the rules for the subscript operator, the expression (*arrPtr)[i]is equivalent to *((*arrPtr)+i). Hence **arrPtr yields the first element of the array, with the index 0.

In order to demonstrate a few operations with the array pointer arrPtr, the following example uses it to address some elements of a two-dimensional array that is, some rows of a matrix:

int matrix[3][10]; // Array of three rows, each with 10 columns. // The array name is a pointer to the first// element; i.e., the first row. arrPtr = matrix; // Let arrPtr point to the first row of// the matrix. (*arrPtr)[0]= 5; // Assign the value 5 to the first element of the // first row.// arrPtr[2][9] = 6; // Assign the value 6 to the last element of the// last row. //++arrPtr; // Advance the pointer to the next row. (*arrPtr)[0]= 7; // Assign the value 7 to the first element of the // second row.

After the initial assignment, arrPtr points to the first row of the matrix, just as the array name matrix does. At this point you can use arrPtr in the same way as matrix to access the elements. For example, the assignment (*arrPtr)[0] = 5 is equivalent to arrPtr[0][0] = 5 or matrix[0][0] = 5.

However, unlike the array name matrix, the pointer name arrPtr does not represent a constant address, as the operation ++arrPtr shows. The increment operation increases the address stored in an array pointer by the size of one array in this case, one row of the matrix, or ten times the number of bytes in an int element.

If you want to pass a multidimensional array to a function, you must declare the corresponding function parameter as a pointer to an array type.

One more word of caution: if a is an array of ten int elements, then you cannot make the pointer from the previous example, arrPtr, point to the array a by this assignment:

arrPtr = a; // Error: mismatched pointer types.

The reason is that an array name, such as a, is implicitly converted into a pointer to the array's first element, not a pointer to the whole array. The pointer to int is not implicitly converted into a pointer to an array of int. The assignment in the example requires an explicit type conversion, specifying the target type int (*)[10] in the cast operator:

arrPtr = (int (*)[10])a; // OK

You can derive this notation for the array pointer type from the declaration of arrPtr by removing the identifier. However, for more readable and more flexible code, it is a good idea to define a simpler name for the type using typedef:

typedef int ARRAY_t[10]; // A type name for "array of ten int elements".ARRAY_t a, // An array of this type, *arrPtr; // and a pointer to this array type.arrPtr = (ARRAY_t *)a; // Let arrPtr point to a.

Pointer arrays

Pointer arrays that is, arrays whose elements have a pointer type are often a handy alternative to two-dimensional arrays. Usually the pointers in such an array point to dynamically allocated memory blocks.

For example, if you need to process strings, you could store them in a two-dimensional array whose row size is large enough to hold the longest string that can occur:

#define ARRAY_LEN 100 #define STRLEN_MAX 256char myStrings[ARRAY_LEN][STRLEN_MAX]= { // Several corollaries of Murphy's Law:"If anything can go wrong, it will.", "Nothing is foolproof, because fools are so ingenious.","Every solution breeds new problems." };

However, this technique wastes memory, as only a small fraction of the 25,600 bytes devoted to the array is actually used. For one thing, a short string leaves most of a row empty; for another, memory is reserved for whole rows that may never be used. A simple solution in such cases is to use an array of pointers that reference the objects in this case, the strings and to allocate memory only for the pointer array and for objects that actually exist. Unused array elements are null pointers.

#define ARRAY_LEN 100 char *myStrPtr[ARRAY_LEN]= // Array of pointers to char { // Several corollaries of Murphy's Law:"If anything can go wrong, it will.", "Nothing is foolproof, because fools are so ingenious.","Every solution breeds new problems." };
Pointer array

The diagram in illustrates how the objects are stored in memory. The pointers not yet used can be made to point to other strings at runtime. The necessary storage can be reserved dynamically in the usual way. The memory can also be released when it is no longer needed.

Questions & Answers

how does Neisseria cause meningitis
Nyibol Reply
what is microbiologist
Muhammad Reply
what is errata
Muhammad
is the branch of biology that deals with the study of microorganisms.
Ntefuni Reply
What is microbiology
Mercy Reply
studies of microbes
Louisiaste
when we takee the specimen which lumbar,spin,
Ziyad Reply
How bacteria create energy to survive?
Muhamad Reply
Bacteria doesn't produce energy they are dependent upon their substrate in case of lack of nutrients they are able to make spores which helps them to sustain in harsh environments
_Adnan
But not all bacteria make spores, l mean Eukaryotic cells have Mitochondria which acts as powerhouse for them, since bacteria don't have it, what is the substitution for it?
Muhamad
they make spores
Louisiaste
what is sporadic nd endemic, epidemic
Aminu Reply
the significance of food webs for disease transmission
Abreham
food webs brings about an infection as an individual depends on number of diseased foods or carriers dully.
Mark
explain assimilatory nitrate reduction
Esinniobiwa Reply
Assimilatory nitrate reduction is a process that occurs in some microorganisms, such as bacteria and archaea, in which nitrate (NO3-) is reduced to nitrite (NO2-), and then further reduced to ammonia (NH3).
Elkana
This process is called assimilatory nitrate reduction because the nitrogen that is produced is incorporated in the cells of microorganisms where it can be used in the synthesis of amino acids and other nitrogen products
Elkana
Examples of thermophilic organisms
Shu Reply
Give Examples of thermophilic organisms
Shu
advantages of normal Flora to the host
Micheal Reply
Prevent foreign microbes to the host
Abubakar
they provide healthier benefits to their hosts
ayesha
They are friends to host only when Host immune system is strong and become enemies when the host immune system is weakened . very bad relationship!
Mark
what is cell
faisal Reply
cell is the smallest unit of life
Fauziya
cell is the smallest unit of life
Akanni
ok
Innocent
cell is the structural and functional unit of life
Hasan
is the fundamental units of Life
Musa
what are emergency diseases
Micheal Reply
There are nothing like emergency disease but there are some common medical emergency which can occur simultaneously like Bleeding,heart attack,Breathing difficulties,severe pain heart stock.Hope you will get my point .Have a nice day ❣️
_Adnan
define infection ,prevention and control
Innocent
I think infection prevention and control is the avoidance of all things we do that gives out break of infections and promotion of health practices that promote life
Lubega
Heyy Lubega hussein where are u from?
_Adnan
en français
Adama
which site have a normal flora
ESTHER Reply
Many sites of the body have it Skin Nasal cavity Oral cavity Gastro intestinal tract
Safaa
skin
Asiina
skin,Oral,Nasal,GIt
Sadik
How can Commensal can Bacteria change into pathogen?
Sadik
How can Commensal Bacteria change into pathogen?
Sadik
all
Tesfaye
by fussion
Asiina
what are the advantages of normal Flora to the host
Micheal
what are the ways of control and prevention of nosocomial infection in the hospital
Micheal
what is inflammation
Shelly Reply
part of a tissue or an organ being wounded or bruised.
Wilfred
what term is used to name and classify microorganisms?
Micheal Reply
Binomial nomenclature
adeolu
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Introduction to computer science. OpenStax CNX. Jul 29, 2009 Download for free at http://cnx.org/content/col10776/1.1
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Introduction to computer science' conversation and receive update notifications?

Ask