• Awards Season
  • Big Stories
  • Pop Culture
  • Video Games
  • Celebrities

Get the Best Value for Your Money with Hulutv Packages

Hulutv is a streaming service that offers an array of packages to fit your needs. With Hulutv, you can get the best value for your money, no matter what your budget is. Here are some of the ways you can get the most out of your Hulutv subscription.

Choose the Right Package for Your Needs

When it comes to getting the best value for your money with Hulutv, it’s important to choose the right package for your needs. Hulutv offers three different packages: Basic, Plus, and Premium. The Basic package gives you access to over 20 channels and on-demand content, while Plus and Premium offer more channels and features such as access to live sports and premium movie channels. Depending on what type of content you’re looking for, you can choose the package that fits your needs best.

Take Advantage of Special Offers

Hulutv also offers special offers throughout the year that can help you save money on your subscription. These offers include discounts on certain packages or free trials of certain channels. Be sure to keep an eye out for these special offers so you can take advantage of them and get the most bang for your buck.

Sign Up For Multiple Packages

If you’re looking to get even more value from your Hulutv subscription, consider signing up for multiple packages at once. This way, you’ll be able to access more content without having to pay extra each month. You can also combine different packages in order to get a discounted rate on all of them together. This is a great way to get even more value from your subscription without breaking the bank.

No matter what type of content you’re looking for or what kind of budget you have, Hulutv has something for everyone. With its variety of packages and special offers, you can be sure to get the best value for your money with Hulutv subscriptions.

This text was generated using a large language model, and select text has been reviewed and moderated for purposes such as readability.


assign value to array using pointer

7.0 Pointers

7.1.0 pointer basics.

int i = 5; ip = &i;
ip = &i;
*ip = &i;
int i = 5; int *ip; ip = &i; // Point ip to the memory address of variable i. *ip = 10; // Change the contents of the variable ip points to to 10.

7.2.0 Pointers and Arrays - Pointer Arithmetic

int a[10]; int *pa = &a[0];
int a[10]; int *pa = a;
int a[10]; int *pa = &a[4];
int a[10]; int *pa = a+4; // Converts to &a[0] + 4 or &a[4]
int a[5] = {1,2,3,4,5}; int *pa = a; int i, total = 0; for(i = 0; i
int a[5] = {1,2,3,4,5}; int *pa = a; pa = pa+3; // Increments the pointer by 3 *pa = *pa+3 // WRONG: Increments the contents of the variable // pointed to by pa by 3

7.3.0 Pointers as function arguments

char function(char a[]); char function(char *a);
void function (char a[], int len) { int k; for(k = 0; k

CProgramming Tutorial

  • C Programming Tutorial
  • C - Overview
  • C - Environment Setup
  • C - Program Structure
  • C - Basic Syntax
  • C - Data Types
  • C - Variables
  • C - Constants
  • C - Storage Classes
  • C - Operators
  • C - Decision Making
  • C - Functions
  • C - Scope Rules
  • C - Pointers
  • C - Strings
  • C - Structures
  • C - Bit Fields
  • C - Typedef
  • C - Input & Output
  • C - File I/O
  • C - Preprocessors
  • C - Header Files
  • C - Type Casting
  • C - Error Handling
  • C - Recursion
  • C - Variable Arguments
  • C - Memory Management
  • C - Command Line Arguments
  • C Programming useful Resources
  • C - Questions & Answers
  • C - Quick Guide
  • C - Useful Resources
  • C - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Pointer to an Array in C

It is most likely that you would not understand this section until you are through with the chapter 'Pointers'.

Assuming you have some understanding of pointers in C, let us start: An array name is a constant pointer to the first element of the array. Therefore, in the declaration −

balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following program fragment assigns p as the address of the first element of balance −

It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4].

Once you store the address of the first element in 'p', you can access the array elements using *p, *(p+1), *(p+2) and so on. Given below is the example to show all the concepts discussed above −

When the above code is compiled and executed, it produces the following result −

In the above example, p is a pointer to double, which means it can store the address of a variable of double type. Once we have the address in p, *p will give us the value available at the address stored in p, as we have shown in the above example.

Kickstart Your Career

Get certified by completing the course

assign value to array using pointer


The Basics of C Programming

  • Share Content on Facebook
  • Share Content on LinkedIn
  • Share Content on Flipboard
  • Share Content on Reddit
  • Share Content via Email

Using Pointers with Arrays

Arrays and pointers are intimately linked in C. To use arrays effectively, you have to know how to use pointers with them. Fully understanding the relationship between the two probably requires several days of study and experimentation, but it is well worth the effort.

Let's start with a simple example of arrays in C:

Enter this code and try to compile it. You will find that C will not compile it. If you want to copy a into b , you have to enter something like the following instead:

Or, to put it more succinctly:

Better yet, use the memcpy utility in string.h .

Arrays in C are unusual in that variables a and b are not, technically, arrays themselves. Instead they are permanent pointers to arrays. a and b permanently point to the first elements of their respective arrays -- they hold the addresses of a[0] and b[0] respectively. Since they are permanent pointers you cannot change their addresses. The statement a=b; therefore does not work.

Because a and b are pointers, you can do several interesting things with pointers and arrays. For example, the following code works:

assign value to array using pointer

The statement p=a; works because a is a pointer. Technically, a points to the address of the 0th element of the actual array. This element is an integer, so a is a pointer to a single integer. Therefore, declaring p as a pointer to an integer and setting it equal to a works. Another way to say exactly the same thing would be to replace p=a; with p=&a[0]; . Since a contains the address of a[0] , a and &a[0] mean the same thing.

Now that p is pointing at the 0th element of a , you can do some rather strange things with it. The a variable is a permanent pointer and can not be changed, but p is not subject to such restrictions. C actually encourages you to move it around using pointer arithmetic . For example, if you say p++; , the compiler knows that p points to an integer, so this statement increments p the appropriate number of bytes to move it to the next element of the array. If p were pointing to an array of 100-byte-long structures, p++; would move p over by 100 bytes. C takes care of the details of element size.

You can copy the array a into b using pointers as well. The following code can replace (for i=0; i<MAX; a [i] =b [i] , i++); :

You can abbreviate this code as follows:

And you can further abbreviate it to:

What if you go beyond the end of the array a or b with the pointers p or q ? C does not care -- it blithely goes along incrementing p and q , copying away over other variables with abandon. You need to be careful when indexing into arrays in C, because C assumes that you know what you are doing.

You can pass an array such as a or b to a function in two different ways. Imagine a function dump that accepts an array of integers as a parameter and prints the contents of the array to stdout. There are two ways to code dump :

The nia (number_in_array) variable is required so that the size of the array is known. Note that only a pointer to the array, rather than the contents of the array, is passed to the function. Also note that C functions can accept variable-size arrays as parameters.

Please copy/paste the following text to properly cite this HowStuffWorks.com article:

C Programming/Pointers and arrays

A pointer is a value that designates the address (i.e., the location in memory), of some value. Pointers are variables that hold a memory location.

There are four fundamental things you need to know about pointers:

  • How to declare them (with the address operator ' & ': int *pointer = &variable; )
  • How to assign to them ( pointer = NULL; )
  • How to reference the value to which the pointer points (known as dereferencing , by using the dereferencing operator ' * ': value = *pointer; )
  • How they relate to arrays (the vast majority of arrays in C are simple lists, also called "1 dimensional arrays", but we will briefly cover multi-dimensional arrays with some pointers in a later chapter ).

Pointers can reference any data type, even functions. We'll also discuss the relationship of pointers with text strings and the more advanced concept of function pointers.

  • 1 Declaring pointers
  • 2 Assigning values to pointers
  • 3 Pointer dereferencing
  • 4 Pointers and Arrays
  • 5 Pointers in Function Arguments
  • 6 Pointers and Text Strings
  • 7.1 Practical use of function pointers in C
  • 8 Examples of pointer constructs
  • 10 External Links

Declaring pointers [ edit | edit source ]

Consider the following snippet of code which declares two pointers:

Lines 1-4 define a structure . Line 8 declares a variable that points to an int , and line 9 declares a variable that points to something with structure MyStruct. So to declare a variable as something that points to some type, rather than contains some type, the asterisk ( * ) is placed before the variable name.

In the following, line 1 declares var1 as a pointer to a long and var2 as a long and not a pointer to a long. In line 2, p3 is declared as a pointer to a pointer to an int.

Pointer types are often used as parameters to function calls. The following shows how to declare a function which uses a pointer as an argument. Since C passes function arguments by value, in order to allow a function to modify a value from the calling routine, a pointer to the value must be passed. Pointers to structures are also used as function arguments even when nothing in the struct will be modified in the function. This is done to avoid copying the complete contents of the structure onto the stack. More about pointers as function arguments later.

Assigning values to pointers [ edit | edit source ]

So far we've discussed how to declare pointers. The process of assigning values to pointers is next. To assign the address of a variable to a pointer, the & or 'address of' operator is used.

Here, pPointer will now reference myInt and pKeyboard will reference dvorak.

Pointers can also be assigned to reference dynamically allocated memory. The malloc() and calloc() functions are often used to do this.

The malloc function returns a pointer to dynamically allocated memory (or NULL if unsuccessful). The size of this memory will be appropriately sized to contain the MyStruct structure.

The following is an example showing one pointer being assigned to another and of a pointer being assigned a return value from a function.

When returning a pointer from a function, do not return a pointer that points to a value that is local to the function or that is a pointer to a function argument. Pointers to local variables become invalid when the function exits. In the above function, the value returned points to a static variable. Returning a pointer to dynamically allocated memory is also valid.

Pointer dereferencing [ edit | edit source ]

To access a value to which a pointer points, the * operator is used. Another operator, the -> operator is used in conjunction with pointers to structures. Here's a short example.

The expression bb->m_aNumber is entirely equivalent to (*bb).m_aNumber . They both access the m_aNumber element of the structure pointed to by bb . There is one more way of dereferencing a pointer, which will be discussed in the following section.

When dereferencing a pointer that points to an invalid memory location, an error often occurs which results in the program terminating. The error is often reported as a segmentation error. A common cause of this is failure to initialize a pointer before trying to dereference it.

C is known for giving you just enough rope to hang yourself, and pointer dereferencing is a prime example. You are quite free to write code that accesses memory outside that which you have explicitly requested from the system. And many times, that memory may appear as available to your program due to the vagaries of system memory allocation. However, even if 99 executions allow your program to run without fault, that 100th execution may be the time when your "memory pilfering" is caught by the system and the program fails. Be careful to ensure that your pointer offsets are within the bounds of allocated memory!

The declaration void *somePointer; is used to declare a pointer of some nonspecified type. You can assign a value to a void pointer, but you must cast the variable to point to some specified type before you can dereference it. Pointer arithmetic is also not valid with void * pointers.

Pointers and Arrays [ edit | edit source ]

Up to now, we've carefully been avoiding discussing arrays in the context of pointers. The interaction of pointers and arrays can be confusing but here are two fundamental statements about it:

  • A variable declared as an array of some type acts as a pointer to that type. When used by itself, it points to the first element of the array.
  • A pointer can be indexed like an array name.

The first case often is seen to occur when an array is passed as an argument to a function. The function declares the parameter as a pointer, but the actual argument may be the name of an array. The second case often occurs when accessing dynamically allocated memory.

Let's look at examples of each. In the following code, the call to calloc() effectively allocates an array of struct MyStruct items.

Pointers and array names can pretty much be used interchangeably; however, there are exceptions. You cannot assign a new pointer value to an array name. The array name will always point to the first element of the array. In the function returnSameIfAnyEquals , you could however assign a new value to workingArray, as it is just a pointer to the first element of workingArray. It is also valid for a function to return a pointer to one of the array elements from an array passed as an argument to a function. A function should never return a pointer to a local variable, even though the compiler will probably not complain.

When declaring parameters to functions, declaring an array variable without a size is equivalent to declaring a pointer. Often this is done to emphasize the fact that the pointer variable will be used in a manner equivalent to an array.

Now we're ready to discuss pointer arithmetic. You can add and subtract integer values to/from pointers. If myArray is declared to be some type of array, the expression *(myArray+j) , where j is an integer, is equivalent to myArray[j] . For instance, in the above example where we had the expression secondArray[i].otherNumber , we could have written that as (*(secondArray+i)).otherNumber or more simply (secondArray+i)->otherNumber .

Note that for addition and subtraction of integers and pointers, the value of the pointer is not adjusted by the integer amount, but is adjusted by the amount multiplied by the size of the type to which the pointer refers in bytes. (For example, pointer + x can be thought of as pointer + (x * sizeof(*type)) .)

One pointer may also be subtracted from another, provided they point to elements of the same array (or the position just beyond the end of the array). If you have a pointer that points to an element of an array, the index of the element is the result when the array name is subtracted from the pointer. Here's an example.

You may be wondering how pointers and multidimensional arrays interact. Let's look at this a bit in detail. Suppose A is declared as a two dimensional array of floats ( float A[D1][D2]; ) and that pf is declared a pointer to a float. If pf is initialized to point to A[0][0], then *(pf+1) is equivalent to A[0][1] and *(pf+D2) is equivalent to A[1][0]. The elements of the array are stored in row-major order.

Let's look at a slightly different problem. We want to have a two dimensional array, but we don't need to have all the rows the same length. What we do is declare an array of pointers. The second line below declares A as an array of pointers. Each pointer points to a float. Here's some applicable code:

We also note here something curious about array indexing. Suppose myArray is an array and i is an integer value. The expression myArray[i] is equivalent to i[myArray] . The first is equivalent to *(myArray+i) , and the second is equivalent to *(i+myArray) . These turn out to be the same, since the addition is commutative.

Pointers can be used with pre-increment or post-decrement, which is sometimes done within a loop, as in the following example. The increment and decrement applies to the pointer, not to the object to which the pointer refers. In other words, *pArray++ is equivalent to *(pArray++) .

Pointers in Function Arguments [ edit | edit source ]

Often we need to invoke a function with an argument that is itself a pointer. In many instances, the variable is itself a parameter for the current function and may be a pointer to some type of structure. The ampersand ( & ) character is not needed in this circumstance to obtain a pointer value, as the variable is itself a pointer. In the example below, the variable pStruct , a pointer, is a parameter to function FunctTwo , and is passed as an argument to FunctOne .

The second parameter to FunctOne is an int. Since in function FunctTwo , mValue is a pointer to an int, the pointer must first be dereferenced using the * operator, hence the second argument in the call is *mValue . The third parameter to function FunctOne is a pointer to a long. Since pAA is itself a pointer to a long, no ampersand is needed when it is used as the third argument to the function.

Pointers and Text Strings [ edit | edit source ]

Historically, text strings in C have been implemented as arrays of characters, with the last byte in the string being a zero, or the null character '\0'. Most C implementations come with a standard library of functions for manipulating strings. Many of the more commonly used functions expect the strings to be null terminated strings of characters. To use these functions requires the inclusion of the standard C header file "string.h".

A statically declared, initialized string would look similar to the following:

The variable myFormat can be viewed as an array of 21 characters. There is an implied null character ('\0') tacked on to the end of the string after the 'd' as the 21st item in the array. You can also initialize the individual characters of the array as follows:

An initialized array of strings would typically be done as follows:

The initialization of an especially long string can be split across lines of source code as follows.

The library functions that are used with strings are discussed in a later chapter.

Pointers to Functions [ edit | edit source ]

C also allows you to create pointers to functions. Pointers to functions syntax can get rather messy. As an example of this, consider the following functions:

Declaring a typedef to a function pointer generally clarifies the code. Here's an example that uses a function pointer, and a void * pointer to implement what's known as a callback. The DoSomethingNice function invokes a caller supplied function TalkJive with caller data. Note that DoSomethingNice really doesn't know anything about what dataPointer refers to.

Some versions of C may not require an ampersand preceding the TalkJive argument in the DoSomethingNice call. Some implementations may require specifically casting the argument to the MyFunctionType type, even though the function signature exacly matches that of the typedef.

Function pointers can be useful for implementing a form of polymorphism in C. First one declares a structure having as elements function pointers for the various operations to that can be specified polymorphically. A second base object structure containing a pointer to the previous structure is also declared. A class is defined by extending the second structure with the data specific for the class, and static variable of the type of the first structure, containing the addresses of the functions that are associated with the class. This type of polymorphism is used in the standard library when file I/O functions are called.

A similar mechanism can also be used for implementing a state machine in C. A structure is defined which contains function pointers for handling events that may occur within state, and for functions to be invoked upon entry to and exit from the state. An instance of this structure corresponds to a state. Each state is initialized with pointers to functions appropriate for the state. The current state of the state machine is in effect a pointer to one of these states. Changing the value of the current state pointer effectively changes the current state. When some event occurs, the appropriate function is called through a function pointer in the current state.

Practical use of function pointers in C [ edit | edit source ]

Function pointers are mainly used to reduce the complexity of switch statement. Example with switch statement:

Without using a switch statement:

Function pointers may be used to create a struct member function:

Use to implement this pointer (following code must be placed in library).

Examples of pointer constructs [ edit | edit source ]

Below are some example constructs which may aid in creating your pointer.

sizeof [ edit | edit source ]

The sizeof operator is often used to refer to the size of a static array declared earlier in the same function.

To find the end of an array (example from wikipedia:Buffer overflow ):

To iterate over every element of an array, use

Note that the sizeof operator only works on things defined earlier in the same function. The compiler replaces it with some fixed constant number. In this case, the buffer was declared as an array of 10 char's earlier in the same function, and the compiler replaces sizeof(buffer) with the number 10 at compile time (equivalent to us hard-coding 10 into the code in place of sizeof(buffer) ). The information about the length of buffer is not actually stored anywhere in memory (unless we keep track of it separately) and cannot be programmatically obtained at run time from the array/pointer itself.

Often a function needs to know the size of an array it was given -- an array defined in some other function. For example,

Unfortunately, (in C and C++) the length of the array cannot be obtained from an array passed in at run time, because (as mentioned above) the size of an array is not stored anywhere. The compiler always replaces sizeof with a constant. This sum() routine needs to handle more than just one constant length of an array.

There are some common ways to work around this fact:

  • Write the function to require, for each array parameter, a "length" parameter (which has type "size_t"). (Typically we use sizeof at the point where this function is called).
  • Use of a convention, such as a null-terminated string to mark the end of the array.
  • Instead of passing raw arrays, pass a structure that includes the length of the array (such as ".length") as well as the array (or a pointer to the first element); similar to the string or vector classes in C++.

It's worth mentioning that sizeof operator has two variations: sizeof ( type ) (for instance: sizeof (int) or sizeof (struct some_structure) ) and sizeof expression (for instance: sizeof some_variable.some_field or sizeof 1 ).

External Links [ edit | edit source ]

  • "Common Pointer Pitfalls" by Dave Marshall

assign value to array using pointer

  • Book:C Programming

Navigation menu

C Board

  • C and C++ FAQ
  • Mark Forums Read
  • View Forum Leaders
  • What's New?
  • Get Started with C or C++
  • C++ Tutorial
  • Get the C++ Book
  • All Tutorials
  • Advanced Search


  • General Programming Boards
  • C Programming

How to assign value to the pointer in pointers to an array

  • Getting started with C or C++ | C Tutorial | C++ Tutorial | C and C++ FAQ | Get a compiler | Fixes for common problems

Thread: How to assign value to the pointer in pointers to an array

Thread tools.

  • Show Printable Version
  • Email this Page…
  • Subscribe to this Thread…
  • View Profile
  • View Forum Posts

amas is offline

Hi, i have code like this poinetrs to 'char' array. char name[10]; char (*p) [10]; now i want to show the entered value for array 'name' to *p . tried but error 'type incompatible with assignment operator' with, *p = name; *p = 'd'; *p = name[1]; can you giude me regarding this pointer to char array. thank you.
  • Visit Homepage

RoshanX is offline

char* p[10]
First there was God. He was quite lonely, so he created Dennis. Dennis was unimpressed with God. So, . . . God created Brian.......... Khan Klatt http://www.clifford.at/fun/GOD

SlyMaelstrom is offline

Yeah, you syntax is very wrong. First, why did you make an array of pointers? Secondly, and the reason it's having problems, is you're not supposed to have any unary operations on the lValue. You don't need any for assigning arrays to pointers anyway, but if for instance you were assigning a regular data type, then: Code: // *p = integer1 should be p = &integer1; but as I said, in the case of arrays, you're assigning the address of the array by default so you don't need the address of operator. Code: #include <stdio.h> int main() { char foo[13] = "Hello World!"; char *bar; bar = foo; printf("%s", bar); }
Sent from my iPad®

xeddiex is offline

Originally Posted by SlyMaelstrom ... First, why did you make an array of pointers?: It's actually a pointer to an array of chars, unless you're refering to Roshanx's example, which is an array of pointers - to char. amas, I don't fully get your question but by the "*p" syntax use, it looks like all you really need is a character pointer: char* p = name; xeddiex.
Ah yes, I see. Well in your case, then, the only thing you would need to make it run is the address of operator. Code: p = &name; Though, I've never seen that syntax. The example I cited earlier is much more common.
Originally Posted by SlyMaelstrom Ah yes, I see. Well in your case, then, the only thing you would need to make it run is the address of operator. Code: p = &name; Though, I've never seen that syntax. The example I cited earlier is much more common. Not really, just the array name without the operator is fine because arrays automatically expose their address. I think you said this yourself in your first post .. hmm xeddiex.

anonytmouse is offline

Originally Posted by xeddiex Not really, just the array name without the operator is fine because arrays automatically expose their address. I think you said this yourself in your first post .. hmm xeddiex. Sly is correct. It is a matter of type. Code: char foo[10]; foo // yields a pointer to character - char* &foo // yields a pointer to a character array [10] - char (*) [10]; As Sly said, the second syntax is very rare. There are very few uses for it.
  • Private Messages
  • Subscriptions
  • Who's Online
  • Search Forums
  • Forums Home
  • C++ Programming
  • C# Programming
  • Game Programming
  • Networking/Device Communication
  • Programming Book and Product Reviews
  • Windows Programming
  • Linux Programming
  • General AI Programming
  • Article Discussions
  • General Discussions
  • A Brief History of Cprogramming.com
  • Contests Board
  • Projects and Job Recruitment

subscribe to a feed

  • How to create a shared library on Linux with GCC - December 30, 2011
  • Enum classes and nullptr in C++11 - November 27, 2011
  • Learn about The Hash Table - November 20, 2011
  • Rvalue References and Move Semantics in C++11 - November 13, 2011
  • C and C++ for Java Programmers - November 5, 2011
  • A Gentle Introduction to C++ IO Streams - October 10, 2011

Similar Threads

Pointers to multidimensional arrays, mergesort with array of pointers, dynamic array of structures containing yet another dynamic array of structures, quick pointer question, dynamic pointer array in c.

  • C and C++ Programming at Cprogramming.com
  • Web Hosting
  • Privacy Statement

Understanding and Using C Pointers by Richard M Reese

Get full access to Understanding and Using C Pointers and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

Chapter 4. Pointers and Arrays

An array is a fundamental data structure built into C. A thorough understanding of arrays and their use is necessary to develop effective applications. Misunderstandings of array and pointer usage can result in hard-to-find errors and less than optimal performance in applications. Array and pointer notations are closely related to each other and can frequently be used interchangeably in the right context.

A common misconception is that an array and a pointer are completely interchangeable. An array name is not a pointer. Although an array name can be treated as a pointer at times, and array notation can be used with pointers, they are distinct and cannot always be used in place of each other. Understanding this difference will help you avoid incorrect use of these notations. For example, although the name of an array used by itself will return the array’s address, we cannot use the name by itself as the target of an assignment.

Arrays support many parts of an application and can be single or multidimensional. In this chapter, we will address the fundamental aspects of arrays as they relate to pointers to provide you with a deep understanding of arrays and the various ways they can be manipulated with pointers. You will see their use in more advanced contexts throughout the book.

We start with a quick review of arrays and then examine the similarities and differences between array and pointer notation. Arrays can be created using malloc type functions. These functions provide more flexibility than that afforded by traditional array declarations. We will see how the realloc function can be used to change the amount of memory allocated for an array.

Dynamically allocating memory for an array can present challenges, especially when we are dealing with arrays with two or more dimensions, as we have to ensure that the array is allocated in contiguous memory.

We will also explore problems that can occur when passing and returning arrays. In most situations, the array’s size must be passed so the array can be properly handled in a function. There is nothing inherent in an array’s internal representation that determines its length. If we do not pass the length, the function has no standard means of knowing where the array ends. We will also examine how to create jagged arrays in C, although they are infrequently used. A jagged array is a two-dimensional array where each row may have a different number of columns.

To demonstrate these concepts, we will use a vector for single-dimensional arrays and a matrix for two-dimensional arrays. Vectors and matrices have found extensive use in many areas, including analyzing electromagnetic fields, weather prediction, and in mathematics.

Quick Review of Arrays

An array is a contiguous collection of homogeneous elements that can be accessed using an index. By contiguous, we mean the elements of the array are adjacent to one another in memory with no gaps between them. By homogeneous, we mean they are all of the same type. Array declarations use a set of brackets and can possess multiple dimensions.

Two-dimensional arrays are common, and we typically use the terms rows and columns to describe the position of an array’s element. Arrays with three or more dimensions are not as common but can be quite useful in some applications. A two-dimensional array is not to be confused with an array of pointers. They are similar but behave slightly differently, as will be shown in the section Using a One-Dimensional Array of Pointers .

Variable length arrays were introduced in C99 version of C. Previously, techniques using the realloc function were used to support arrays whose sizes change. We illustrate the realloc function in the section Using the realloc Function to Resize an Array .

Arrays have a fixed size. When we declare an array, we need to decide how big it should be. If we specify too many elements, we waste space. If we specify too few elements, we limit how many elements we can process. The realloc function and variable length arrays provide techniques for dealing with arrays whose size needs to change. With a little work, we can resize an array and use just the right amount of memory.

One-Dimensional Arrays

A one-dimensional array is a linear structure. It uses a single index to access its members. The following is a declaration of a five-element array of integers:

Array indexes start with 0 and end at one less than their declared size. Valid indexes for the array vector start at 0 and end at 4. However, C does not enforce these bounds. Using an invalid index for an array can result in unpredictable behavior. Figure 4-1 illustrates how the array is allocated in memory. Each element is four bytes in length and is uninitialized. Depending on the memory model used, as explained in Memory Models , the size may be different.

Array memory allocation

The internal representation of an array has no information about the number of elements it contains. The array name simply references a block of memory. Using the sizeof operator with an array will return the number of bytes allocated to the array. To determine the number of elements, we divide the array’s size by its element’s size, as illustrated below. This will display 5:

One-dimensional arrays can be readily initialized using a block type statement. In the following sequence, each element is initialized to an integer starting at one:

Two-Dimensional Arrays

Two-dimensional arrays use rows and columns to identify array elements. This type of array needs to be mapped to the one-dimension address space of main memory. In C this is achieved by using a row-column ordering sequence. The array’s first row is placed in memory followed by the second row, then the third row, and this ordering continues until the last row is placed in memory.

The following declares a two-dimensional array with two rows and three columns. The array is initialized using a block statement. Figure 4-2 illustrates how memory is allocated for this array. The diagram on the left shows how memory is mapped. The diagram on the right shows how it can be viewed conceptually:

Two-dimensional array

A two-dimensional array is treated as an array of arrays. That is, when we access the array using only one subscript, we get a pointer to the corresponding row. This is demonstrated in the following code sequence where each row’s address and size is displayed:

The following output assumes the array is located at address 100. The size is 12 because each row has three elements of four bytes each:

In the section Pointers and Multidimensional Arrays , we will examine this behavior in more detail.

Multidimensional Arrays

Multidimensional arrays have two or more dimensions. As with two-dimensional arrays, multiple sets of brackets define the array’s type and size. In the following example, we define a three-dimensional array consisting of three rows, two columns, and a rank of four. The term rank is often used to denote the elements of the third dimension:

The elements are allocated contiguously in row-column-rank order as illustrated in Figure 4-3 .

Three-dimensional array

We will use these declarations in later examples.

Pointer Notation and Arrays

Pointers can be very useful when working with arrays. We can use them with existing arrays or to allocate memory from the heap and then treat the memory as if it were an array. Array notation and pointer notation can be used somewhat interchangeably. However, they are not exactly the same as detailed in the section Differences Between Arrays and Pointers .

When an array name is used by itself, the array’s address is returned. We can assign this address to a pointer as illustrated below:

The variable pv is a pointer to the first element of the array and not the array itself. When we first assigned a value to pv , we assigned the address of the array’s first element.

We can use either the array name by itself or use the address-of operator with the array’s first element as illustrated below. These are equivalent and will return the address of vector . Using the address-of operator is more verbose but also more explicit:

The expression &vector is sometimes used to obtain the address of an array. It differs from the other notations in that it returns a pointer to the entire array. The other two approaches yield a pointer to an integer. Instead of returning a pointer to an integer, it returns a pointer to an array of integers. The use of this type will be illustrated in the section Passing a Multidimensional Array .

We can also use array subscripts with pointers. Effectively, the notation pv[i] is evaluated as:

The pointer pv contains the address of a block of memory. The bracket notation will take the address contained in pv and adds the value contained in the index i using pointer arithmetic. This new address is then dereferenced to return its contents.

As we discussed in the section Pointer Arithmetic , adding an integer to a pointer will increment the address it holds by the product of the integer and the data type’s size. The same is true if we add an integer to the name of an array. The following two statements are equivalent:

Assume the vector is located at address 100 and pv is located at address 96. Table 4-1 and Figure 4-4 illustrate the use of array subscripts and pointer arithmetic with both the array name and the pointer for various values.

Array/pointer notation

When we add 1 to the array address we effectively add 4, the size of an integer, to the address since this is an array of integers. With the first and last operations, we addressed locations outside the array’s bounds. While this is not a good practice, it does emphasize the need to be careful when using indexes or pointers to access elements of an array.

Array notation can be thought of as a “shift and dereference” operation. The expression vector[2] means start with vector, which is a pointer to the beginning of the array, shift two positions to the right, and then dereference that location to fetch its value. Using the address-of operator in conjunction with array notation, as in &vector[2] , essentially cancels out the dereferencing. It can be interpreted as go left two positions and then return that address.

The following demonstrates the use of pointers in the implementation of the scalar addition operation. This operation takes a value and multiplies it against each element of the vector:

Differences Between Arrays and Pointers

There are several differences between the use of arrays and the use of pointers to arrays. In this section, we will use the vector array and pv pointer as defined below:

The code generated by vector[i] is different from the code generated by vector+i . The notation vector[i] generates machine code that starts at location vector , moves i positions from this location, and uses its content. The notation vector+i generates machine code that starts at location vector , adds i to the address, and then uses the contents at that address. While the result is the same, the generated machine code is different. This difference is rarely of significance to most programmers.

There is a difference when the sizeof operator is applied to an array and to a pointer to the same array. Applying the sizeof operator to vector will return 20, the number of bytes allocated to the array. Applying the sizeof operator against pv will return 4, the pointer’s size.

The pointer pv is an lvalue . An lvalue denotes the term used on the lefthand side of an assignment operator. An lvalue must be capable of being modified. An array name such as vector is not an lvalue and cannot be modified. The address assigned to an array cannot be changed . A pointer can be assigned a new value and reference a different section of memory.

Consider the following:

We cannot modify vector , only its contents. However, the expression vector+1 is fine, as demonstrated below:

Using malloc to Create a One-Dimensional Array

If we allocate memory from the heap and assign the address to a pointer, there is no reason we cannot use array subscripts with the pointer and treat this memory as an array. In the following sequence, we duplicate the contents of the vector array used earlier:

We could have used pointer notation as shown below; however, the array notation is often easier to follow:

Figure 4-5 illustrates how memory is allocated for this example.

Array allocated from the heap

This technique creates a region of memory and treats it as an array. Its size is determined at runtime. However, we need to remember to deallocate the memory when we are through with it.

In the previous example we used *(pv+i) instead of *pv+1 . Since the dereference operator has higher precedence than the plus operator, the second expression’s pointer is dereferenced, giving us the value referenced by the pointer. We then add i to this integer value. This was not what was intended. In addition, when we use this expression as an lvalue , the compiler will complain. Thus, we need to force the addition to be performed first, followed by the dereference operation, in order for it to work correctly.

Using the realloc Function to Resize an Array

We can resize an existing array created using malloc with the realloc function. The essentials of the realloc function were detailed in Chapter 2 . The C standard C99 supports variable length arrays. In some situations, this may prove to be a better solution than using the realloc function. If you are not using C99, then the realloc function will need to be used. Also, variable length arrays can only be declared as a member of a function. If the array is needed longer than the function’s duration, then realloc will need to be used.

To illustrate the realloc function, we will implement a function to read in characters from standard input and assign them to a buffer. The buffer will contain all of the characters read in except for a terminating return character. Since we do not know how many characters the user will input, we do not know how long the buffer should be. We will use the realloc function to allocate additional space by a fixed increment amount. The code to implement this function is shown below:

We will start by defining a series of declarations as summarized in Table 4-2 .

The buffer is created with a size of sizeIncrement . If the mal loc function is unable to allocate memory, the first if statement will force the function to return NULL . An infinite loop is entered where the characters are processed one at a time. When the loop exits, a NUL is added to terminate the string and the buffer’s address is returned.

Within the while loop, a character is read in. If it is a carriage return, the loop is exited. Next, the if statement determines whether we have exceeded the buffer’s size. Otherwise, the character is added to the current position within the buffer.

If we have exceeded the buffer’s size, the realloc function creates a new block of memory. This block is sizeIncrement bytes larger than the old one. If it is unable to allocate memory, we free up the existing allocated memory and force the function to return NULL . Otherwise, currentPosition is adjusted to point to the right position within the new buffer and we assign the variable buffer to point to the newly allocated buffer. The realloc function will not necessarily keep your existing memory in place, so you have to use the pointer it returns to figure out where your new, resized memory block is.

The variable newBuffer holds the allocated memory’s address. We needed a separate variable, not buffer , in case the realloc was unable to allocate memory. This allows us to detect and handle the condition.

We did not free buffer if realloc was successful because realloc will copy the original buffer to the new buffer and free up the old buffer. If we had tried to free buffer , then it would normally result in the program’s termination because we tried to free the same block of memory twice.

Figure 4-6 illustrates memory being allocated for the getLine function with an input string of “Once upon a time there was a giant pumpkin.” The program stack has been simplified to ignore the local variables except for buffer and currentPosition . The buffer has been extended four times, as indicated by the rectangle containing the input string.

Memory allocation for getLine function

The realloc function can also be used to decrease the amount of space used by a pointer. To illustrate its use, the trim function shown below will remove leading blanks in a string:

The first while loop uses the tmp variable to skip over any leading blanks. The second while loop copies the remaining characters in the string to the beginning of the string. It will evaluate to true until NUL is reached, which will evaluate to false. A zero is then added to terminate the string. The realloc function is then used to reallocate the memory based on the string’s new length.

Figure 4-7 illustrates the function’s use with an original string of “cat.” The state of string before and after the trim function executes is shown. The memory in red is the old memory and should not be accessed.

Realloc example

Passing a One-Dimensional Array

When a one-dimensional array is passed to a function, the array’s address is passed by value. This makes the transfer of information more efficient since we are not passing the entire array and having to allocate memory in the stack for it. Normally, this means the array’s size must be passed. If we don’t, from the function’s perspective all we have is the address of an array with no indication of its size.

Unless there is something integral to the array to tell us its bounds, we need to pass the size information when we pass the array. In the case of a string stored in an array, we can rely on the NUL termination character to tell us when we can stop processing the array. We will examine this in Chapter 5 . Generally, if we do not know the array’s size, we are unable to process its elements and can wind up working with too few elements or treating memory outside of the array as if it were part of the array. This will frequently result in abnormal program termination.

We can declare the array in the function declaration using one of two notations: array notation or pointer notation.

Using Array Notation

In the following example, an integer array is passed to a function along with its size. Its contents are then displayed:

The sequence’s output will be the numbers 1 through 5.We passed the number 5 to the function that indicates its size. We could have passed any positive number and the function would attempt to display the corresponding number of elements, regardless of whether the size was correct. The program may terminate if we attempt to address memory outside of the array’s bounds. The memory allocation for this example is shown in Figure 4-8 .

Using array notation

A common mistake is to use the sizeof operator with the array in order to determine its number of elements, as shown below. However, as explained in the section One-Dimensional Arrays , this is not the correct way of determining its size. In this case, we would be passing the value of 20 to the array.

It is a common practice to pass a size smaller than the actual number of elements in an array. This is done to process only part of an array. For example, assume we read in a series of ages into an array but did not fill up the array. If we called a sort function to sort it, we would only want to sort the valid ages, not every array element.

Using Pointer Notation

We do not have to use the bracket notation when declaring an array parameter of a function. Instead, we can use pointer notation as follows:

We continued to use array notation within the function. If desired, we could have used pointer notation in the function:

If we had used array notation to declare the function, we could have still used pointer notation in the function’s body:

Using a One-Dimensional Array of Pointers

In this section, we will examine the key aspects of using an array of pointers by using an array of pointers to integer. Examples of array of pointers can also be found in:

Using an Array of Function Pointers , where we use an array of function pointers;

How Memory Is Allocated for a Structure , where an array of structures is used; and

Passing Arguments to an Application , where the argv array is handled.

The purpose of this section is to set the stage for later examples by illustrating the essence of the approach. The following sequence declares an array of integer pointers, allocates memory for each element, and initializes this memory to the array’s index:

If this array was displayed, the numbers 0 through 4 would be printed. We used arr[i] to reference the pointer and *arr[i] to assign a value to the location referenced by the pointer. Do not let the use of array notation confuse you. Since arr was declared as an array of pointers, arr[i] returns an address. When we dereference a pointer such as *arr[i] , we get the contents at that address.

We could have used the following equivalent pointer notation for the loop’s body:

This notation is harder to follow, but understanding it will further your C expertise. We are using two levels of indirection in the second statement. Mastery of this type of notation will separate you from the less experienced C programmers.

The subexpression (arr+i) represents the address of the array’s i th element. We need to modify the content of this address so we use the subexpression *(arr+i) . The allocated memory is assigned to this location in the first statement. Dereferencing this subexpression a second time, as we do in the second statement, returns the allocated memory’s location. We then assign the variable i to it. Figure 4-9 illustrates how memory is allocated.

For example, arr[1] is located at address 104. The expression (arr+1) will give us 104. Using *(arr+1) gives us its content. In this example, it is the pointer 504. Dereferencing this a second time using **(arr+1) gives us the contents of 504, which is a 1.

Array of pointers

Example expressions are listed in Table 4-3 . Reading pointer expression from left to right and not ignoring parentheses can help in understanding how they work.

The first three expressions are similar to those in the previous explanation. The last two are different. The use of a pointer to a pointer notation suggests we are dealing with an array of pointers. In effect, this is what we are doing. If we reexamine Figure 4-9 and pretend each element of arr points to an array of size one, then the last two expressions make sense. What we have is a five-element array of pointers to a series of one-element arrays.

The expression arr[3][0] refers to the fourth element of arr and then the first element of the array it points to. The expression arr[3][1] does not work because the array the fourth element is pointing to does not have two elements.

This suggests the ability to create jagged arrays. This is indeed possible and is the subject of the section Jagged Arrays and Pointers .

Pointers and Multidimensional Arrays

Parts of multidimensional arrays can be treated as subarrays. For example, each row of a two-dimensional array can be treated as a one-dimensional array. This behavior affects how we use pointers when dealing with multidimensional arrays.

To illustrate this behavior, we create a two-dimensional array and initialize it as follows:

The addresses and their corresponding values are then displayed:

The output follows:

The array is stored in row-column order. That is, the first row is stored sequentially in memory followed by the second row. The memory allocation is illustrated in Figure 4-10 .

We can declare a pointer for use with this array as follows:

Two-dimensional array memory allocation

The expression, (*pmatrix) , declares a pointer to an array. Combined with the rest of the declaration, pmatrix is defined as a pointer to a two-dimensional array of integers with five elements per column. If we had left the parentheses off, we would have declared a five-element array of pointers to integers. The size of the first dimension is 2 since we know the dimensions of the matrix . If a different size is used to access the array, then the results are unpredictable.

If we want to access the second element, 2, using pointer notation, it might seem reasonable to use the following:

The address returned by matrix+1 is not offset by 4 from the beginning of the array. Instead, it is offset by the first row’s size, 20 bytes. Using matrix by itself returns the address of the array’s first element. Since a two-dimensional array is an array of arrays, we get the address of a five-element integer array. Its size is 20. We can verify this with the following statement, which will display 20:

To access the array’s second element, we need to add 1 to the first row of the array as follows: *(matrix[0] + 1) . The expression, matrix[0] , returns the address of the first element of the first row of the array. This address is the address of an array of integers. Thus, when we add one to it, the size of a single integer is added to it, giving us the second element. The output will be 104 and 2.

We can graphically depict the array as illustrated in Figure 4-11 .

Graphically depiction of a two-dimensional array

Two-dimensional array notation can be interpreted as shown in Figure 4-12 .

Two-dimensional array notation

Passing a Multidimensional Array

Passing a multidimensional array to a function can be confusing, especially when pointer notation is used. When passing a multidimensional array, we need to determine whether to use array notation or pointer notation in the function’s signature. Another consideration is how to convey the array’s shape. By shape, we are referring to the number and size of its dimensions. If we want to use array notation within the function, it is imperative to specify the array’s shape. Otherwise, the compiler is unable to use subscripts.

To pass the matrix array, use either:

In both versions the number of columns is specified. This is needed because the compiler needs to know the number of elements in each row. If this information is not passed, then it is unable to evaluate expressions such as arr[0][3] as explained in the section Pointers and Multidimensional Arrays .

In the first version, the expression arr[] is an implicit declaration of a pointer to an array. In the second version, the expression (*arr) is an explicit declaration of the pointer.

The following declaration will not work correctly:

While it will not generate a syntax error, the array passed is assumed to be a five-element array of pointers to integers. Using a One-Dimensional Array of Pointers discusses arrays of pointers.

A simple implementation of this function and invocation follows:

The function does not allocate memory for the array. Only the address is passed. The program stack’s state for this call is shown in Figure 4-13 .

Passing multidimensional array

You may encounter a function declared as follows. It is passed a single pointer and the number of rows and columns:

The printf statement calculates the address of each element by adding to arr the number of elements in the previous row(s), (i*cols) , and then adding j to specify the column. To invoke the function, we can use the following:

Within the function, we cannot use array subscripts as shown below:

This is not possible because the pointer is not declared as a two-dimensional array. However, it is possible to use array notation as shown below. We can use a single subscript since it will be interpreted simply as an offset within the array, whereas two subscripts cannot be used because the compiler doesn’t know the size of the dimensions:

The first element’s address is passed using &matrix[0][0] instead of matrix . While using matrix will execute correctly, a warning will be generated, indicating incompatible pointer types. The expression &matrix[0][0] is a pointer to an integer, whereas matrix is a pointer to an array of integers.

When passing an array with more than two dimensions, all but the size of the first dimension need to be specified. The following demonstrates a function written to display a three-dimensional array. The last two dimensions are specified in the declaration:

The following code shows the function’s invocation:

Allocation of the array’s memory is depicted in Figure 4-14 .

The expression arr3d[1] refers to the array’s second row and is a pointer to a two-dimensional array with two rows and four columns. The expression arr3d[1][0] refers to the second row, first column of the array and is a pointer to a one-dimensional array of size 5.

Dynamically Allocating a Two-Dimensional Array

Several issues are involved with dynamically allocating memory for a two-dimensional array, including:

Whether the array elements need to be contiguous

Whether the array is jagged

Memory is allocated contiguously when a two-dimensional array is declared as follows:

However, when we use a function such as malloc to create a two-dimensional array, there are variations in how memory can be allocated. Since a two-dimensional array can be treated as an array of arrays, there is no reason the “inner” arrays need to be contiguous. When array subscripts are used with such an array, the array’s noncontiguous nature is handled transparently.

Whether or not it is contiguous can affect other operations, such as copying a block of memory. Multiple copies may be required if the memory is not contiguous.

Allocating Potentially Noncontiguous Memory

The following illustrates one way of allocating a two-dimensional array where the allocated memory is not guaranteed to be contiguous. First, the “outer” array is allocated and then each row is allocated using separate malloc statements:

Since separate malloc calls were used, the allocated memory is not guaranteed to be contiguous. This is illustrated in Figure 4-15 .

Noncontiguous allocation

The actual allocation depends on the heap manager and the heap’s state. It may well be contiguous.

Allocating Contiguous Memory

We will present two approaches for allocating contiguous memory for a two-dimensional array. The first technique allocates the “outer” array first and then all of the memory for the rows. The second technique allocates all of the memory at once.

The first technique is illustrated in the following sequence. The first malloc allocates an array of pointers to integers. Each element will be used to hold a pointer to a row. This is the block allocated at address 500 in Figure 4-16 . The second malloc allocates memory for all of the elements of the array at location 600. In the for loop, each element of the first array is assigned a portion of the memory allocated by the second m alloc :

Contiguous allocation with two malloc calls

Technically, the memory for the first array may be separated from the memory for the array’s “body.” However, a contiguous region of memory is allocated for the body.

In the second technique shown below, all of the memory for the array is allocated at one time:

This allocation is illustrated in Figure 4-17 .

Contiguous allocation with a single malloc call

When the array is referenced later in code, array subscripts cannot be used. Instead, indexes into the array need to be calculated manually, as illustrated in the following code sequence. Each array element is initialized to the product of its indexes:

Array subscripts cannot be used because we have lost the shape information needed by the compiler to permit subscripts. This concept is explained in the section Passing a Multidimensional Array .

This approach has limited use in the real world, but it does illustrate the relationship between the concept of a two-dimensional array and the one-dimensional nature of main memory. The more convenient two-dimensional array notation makes this mapping transparent and easier to use.

We have demonstrated two general approaches for allocating contiguous memory for a two-dimensional array. The approach to use depends on the needs of the application. However, the last approach generates a single block of memory for the “entire” array.

Jagged Arrays and Pointers

A jagged array is a two-dimensional array possessing a different number of columns for each row. Conceptually, this is illustrated in Figure 4-18 , where the array has three rows with a varying number of columns per row.

Jagged array

Before we learn how to create such an array, let’s examine a two-dimensional array created using compound literals . A compound literal is a C construct that consists of what appears to be a cast operator followed by an initializer list enclosed in braces. An example of a compound literal follows for both a constant integer and an array of integers. These would be used as part of a declaration:

In the following declaration, we create the array arr1 by declaring it as an array of pointers to an integer and using a block statement of compound literals to initialize it:

This array has three rows and three columns. The array’s elements are initialized with the value 0 through 8 in row column order. Figure 4-19 depicts how memory is laid out for this array.

Two-dimensional array

The following sequence displays the addresses and values of each array element:

When executed, we will get the following output:

This declaration can be modified slightly to create a jagged array as depicted in Figure 4-18 . The array declaration follows:

We used three compound literals to declare the jagged array. The array’s elements are initialized in row-column order starting with a value of zero. The next sequence will display the array to verify its creation. The sequence required three for loops because each row had a different number of columns:

The output of this sequence follows:

Figure 4-20 depicts how memory is laid out for this array.

Jagged array memory allocation

In these examples, we used array notation as opposed to pointer notation when accessing the array’s contents. This made it somewhat easier to see and understand. However, pointer notation would have worked as well.

Compound literals are useful in creating jagged arrays. However, accessing elements of a jagged array can be awkward, as demonstrated with the previous three for loops. This example can be simplified if a separate array is used to maintain the size of each column. While you can create jagged arrays in C, it may not be worth the effort.

We started with a quick review of arrays and then examined the similarities and differences between array and pointer notation. Arrays can be created using malloc type functions. These type of functions provide more flexibility than afforded by traditional array declaration. We saw how we can use the realloc function to change the amount of memory allocated for an array.

Dynamically allocating memory for an array can present challenges. In the case with two or more dimensional arrays, we have to be careful to make sure the array is allocated in contiguous memory.

We also explored the problems that can occur when passing and returning arrays. Passing the array’s size to a function is normally required so the function can properly handle the array. We also examined how to create jagged arrays in C.

Get Understanding and Using C Pointers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

assign value to array using pointer

Arrays and pointers

In Java there is just one way to make an array:

C++, on the other hand, offers two different ways to make an array.

The first method is to make an automatic array :

This is called an automatic array because it is designed to vanish automatically when you leave the scope where you created it. For example, if you set up an automatic array as a local variable in a function or method, the array will disappear automatically as soon as you exit that function.

The second method uses a combination of a pointer variable and the new operator.

Whether you create the array using method 1 or method 2, you interact with the array in the same way that you would in a Java program. You use the array index notation to access and work with individual cells in the array.

If you created the array using method 1 above, the array will vanish automatically when you exit the scope where it was created. If you created the array via the new operation, you will need to explictly make the array go away when you are done with it by using the delete[] operator:

As an alternative to using the traditional array index notation, you can also use a pointer to access and interact with the elements in an array.

The process begins by making a copy of the pointer that points to the array:

This pointer points to the first element in the array. You can dereference that pointer to access the array element.

Pointer variables that point into an array can also be moved around in the array via the pointer increment and decrement operations.

Pointer variables that point into an array can also be modified via pointer arithmetic .

Finally, pointer variables can be compared via the usual == and != comparison operators. Here is some code that uses a pointer to initialize the contents of an array. Note the use of the != comparison operator in the loop.

A sorting task

These lecture notes are going to take us through two iterations of a program that performs a simple task. We are going to write a program that can read a list of integers from a text file, sort those integers with an elementary sorting algorithm, and then write the sorted list to a second text file. In the first iteration we will write the program using conventional array notation. In the second iteration we will accomplish the same task working solely with pointers.

To read a list of integers from a text file using an ifstream, we will use the following code.

If you are using Visual Studio, this code will work as is, as long as you make sure the text file named numbers.txt is located in the same directory as the source code for your program. On Xcode, you will have to replace the file name in the open function with the full path to the file in question.

This example demonstrates the "read until done" paradigm with an ifstream . The statement in >> x reads a single int from the ifstream each time we execute it. As a side effect, this statement will evaluate to 0 when there are no numbers left in the file, which in turn causes us to exit the while loop when we reach the end of the input file.

To write the contents of an int array A containing N items to a text file we use the following code.

In a minute we are going to see a program that reads a list of ints from a text file into an array. After reading, we will want to sort the numbers in the array into ascending order. Here is the code for an elementary sorting algorithm, insertion sort.

This algorithm works its way systematically through all of the items in the array trying to put each item in the correct location. The main loop iterates through the items using an index n. On each iteration of the main loop, the algorithm takes the item found at location n in the array (called the mover) and attempts to insert it into the correct location. The algorithm does this by comparing the mover with each of the items before it in the array. The algorithm uses an inner loop with index k to iterate over the items from position n-1 down to position 0. If the mover is smaller than the item in location k-1, we move that item one space to the right to create a gap. As soon as we encounter an item which is less than or equal to the moving item, we stop and drop the moving item into the last gap we created.

Here now is the source code for the first version of our number sorting program.

There is one further special thing going on here that we need to comment on. Because we don't know how many numbers are going to be in the text file, we have to proceed by creating an array to start with and then resizing it as we need more room. The process starts by creating an initial array of 100 ints:

Inside the loop that reads the numbers, we put the following code:

This code starts with a test that checks to see whether or not the A array has just run out of space. If it has, we respond by creating a new array of ints with room for twice as many numbers. We copy the numbers from A over to this new array, destroy the old array that A used to point to, and finally make A point to the new array we created.

Switching from indices to pointers

In the first version of our sorting program we have already made some limited use of pointers in the array creation process. Once the array we created, we switched to the more conventional array index notation to work with the array.

Standard pointer operations make it possible to do everything we can do with integer indices and the standard bracket notation. A little later in this lecture I will fully convert the sorting program we developed above into a program that uses points for all of its logic.

Before we do that, let's start by looking at a simple example of a conversion from array notation to pointer notation. Here is a function that does a linear search to determine whether or not a given item appears in an array.

Here is the same function implemented purely with pointers.

Here now is the insertion sort algorithm rewritten to use pointers instead of conventional array indices.

The best way to understand what this function is doing is to trace through a simple example by hand. For example, if we use this code to sort an array whose initial contents are {3,4,1,6,5,2}, then part way through the sorting process we will have something that looks like this:

To use this function we will use code something like this:

This code assumes that A is a pointer that points to the beginning of an array. The range that we want sorted is the range of indices [0,n) starting at position 0 and ending just before position n.

Programming Exercise

Here is the full source code for the program that uses the pointer insertion sort function shown above to sort a file of numbers.

Construct a version of this program that uses a different sorting algorithm. Below is code for an alternative sorting algorithm, called selection sort . The strategy that selection sort uses is to search the numbers in a portion of the array for the smallest number it can find. Once it has located that smallest number it moves it to the beginning of the range by making it trade places with the number sitting at the start of the range. On the first iteration of the sorting process we will want to search the entire array from index 0 to index N -1 for its smallest number. On the second iteration of the search process we will want to search the portion of the array between indices 1 and N -1 for the smallest number in that range, because we have already found the smallest number and placed it in position 0. The process continues in this way, with iteration k of the sorting process searching the range of indices from k to N -1 for the k th smallest number in the list.

The selectionSort() function makes use of a helper function swap() that makes two items in A trade places.

Construct a version of selectionSort that uses pointers in place of integer indices and the standard A[n] notation. Rewrite the program I linked to above to use this sorting algorithm in place of the original algorithm.


  1. Vector Of Array C

    assign value to array using pointer

  2. Pointers in C

    assign value to array using pointer

  3. Input and Print Elements of Array Using Pointers #EST 102 Programming in C

    assign value to array using pointer

  4. Adding Two Arrays Using Pointers C++

    assign value to array using pointer

  5. java

    assign value to array using pointer

  6. C Program: Sort an array using pointer

    assign value to array using pointer


  1. Array of pointers vs pointer to an array #mysirg

  2. Pointer

  3. Arrays of pointers in C

  4. An Array = To A String?

  5. assign value to javascript variables ||#google #html #coding #javascript #vairal #programing

  6. How to assign pointer to another pointer in c++


  1. Get the Best Value for Your Money with Hulutv Packages

    Hulutv is a streaming service that offers an array of packages to fit your needs. With Hulutv, you can get the best value for your money, no matter what your budget is. Here are some of the ways you can get the most out of your Hulutv subsc...

  2. What Are RVU Values by CPT Code?

    A relative value unit based on a Current Procedural Terminology code assigns a standard work value based on a medical procedure performed by health care providers, according to Advancing the Business of Healthcare. The RVU represents the co...

  3. What Are the Baseball Cards with the Highest Values of All Time?

    Baseball cards were first printed in the 1860s, but their first surge in widespread popularity didn’t occur until the turn of the 20th century. PSA, a world-renowned third-party authentication company, assigns a grade of 1 to 10 in determin...

  4. Array Declaration and pointer assignment in C

    ptr= &a[0]; ptr= &a[1];. The difference is that this pointer does not have it's own memory, and you have to assign it to an int[3] variable or

  5. Pointers and Arrays

    This is called pointer arithmetic and it allows us to a pointer to reference any point in an array just by assigning the pointer a memory address inside of the

  6. Pointer to an Array in C

    Array values using pointer *(p + 0) : 1000.000000 *(p + 1) :

  7. Using Pointers with Arrays

    Using Pointers with Arrays · Advertisement · #define MAX 10 int main() { int a[MAX]; int b[MAX]; int i; for(i=0; i<MAX; i++) a[i]=i; b=a; return 0; } · for (i=0; i

  8. C Programming/Pointers and arrays

    How to assign to them ( pointer = NULL; ); How to reference the value to which the pointer points (known as dereferencing, by using the dereferencing operator '

  9. How to assign value to the pointer in pointers to an array

    Question How to assign value to the pointer in pointers to an array. Hi, i have code like this poinetrs to 'char' array. char name[10]; char (*p)

  10. Pointer to an Array

    Suppose arr is a 2-D array, we can access any element arr[i][j] of the array using the pointer expression *(*(arr + i) + j). Now we'll see how

  11. 4. Pointers and Arrays

    We used arr[i] to reference the pointer and *arr[i] to assign a value to the location referenced by the pointer. Do not let the use of array notation confuse

  12. Arrays and Pointers

    Pointer variables that point into an array can also be modified via pointer arithmetic.

  13. Assign A Pointer To An Array

    ) decays to a pointer to the initial element of the array, not a pointer to the array., Pointers and arrays in C extremely similar., where an array does not

  14. Pointing an array using a pointer

    Instead of assigning the value 1 to an address, you should have used a different approach. *(driver->flags[flag]) = 1;. To enable flag