Solved

# integerArray is a pointer

Posted on 2014-09-21
177 Views
``````// ArrayDemo - demonstrate the use of arrays
//             by reading a sequence of integers
//             and then displaying them and their sum
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

// prototype declarations
int readArray(int integerArray[], int maxNumElements);
int sumArray(int integerArray[], int numElements);
void displayArray(int integerArray[], int numElements);

int main(int nNumberofArgs, char* pszArgs[])
{
// input the loop count
cout << "This program sums values entered "
<< "by the user\n";
cout << "Terminate the loop by entering "
<< "a negative number\n";
cout << endl;

// read numbers to be summed from the user into a
// local array
int inputValues[128];
int numberOfValues = readArray(inputValues, 128);

// now output the values and the sum of the values
displayArray(inputValues, numberOfValues);
cout << "The sum is "
<< sumArray(inputValues, numberOfValues)
<< endl;

// wait until user is ready before terminating program
// to allow the user to see the program results
cout << "Press Enter to continue..." << endl;
cin.ignore(10, '\n');
cin.get();
return 0;
}

// readArray - read integers from the operator into
//             'integerArray' until operator enters neg.
//             Return the number of elements stored.
int readArray(int integerArray[], int maxNumElements)
{
int numberOfValues;
for(numberOfValues = 0;
numberOfValues < maxNumElements;
numberOfValues++)
{
// fetch another number
int integerValue;
cout << "Enter next number: ";
cin  >> integerValue;

// if it's negative...
if (integerValue < 0)
{
// ...then exit
break;
}

// ... otherwise store the number
// into the  storage array
integerArray[numberOfValues] = integerValue;
}

// return the number of elements read
return numberOfValues;
}

// displayArray - display the members of an
//                array of length sizeOfloatArray
void displayArray(int integerArray[], int numElements)
{
cout << "The value of the array is:" << endl;
for (int i = 0; i < numElements; i++)
{
cout << i << ": " << integerArray[i] << endl;
}
cout << endl;
}

// sumArray - return the sum of the members of an
//            integer array
int sumArray(int integerArray[], int numElements)
{
int accumulator = 0;
for (int i = 0; i < numElements; i++)
{
accumulator += integerArray[i];
}
return accumulator;
}
``````

integerArray      0x0034fb28 {3}      int *
maintains the first integerValue

I do not understand that -            integerArray      0x0034fb28 {3}      int *
is a pointer

why is this always the first value (3 in this example)
0
Question by:rgb192
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• Learn & ask questions
• 3
• 2
• 2
• +3

LVL 27

Accepted Solution

Sinisa Vuk earned 63 total points
ID: 40336008
pointer to array is exact the same as pointer to some integer value - but point to first value in array - so if you sorted before - it is always 3.  (ex: array ->[3],5,6,8,... )
0

LVL 14

Assisted Solution

frankhelk earned 187 total points
ID: 40336195
The language C (from which C++ inherited the structure) was designed for efficiency, and the concept of arrays is one expression of that guideline. All that the management of an array needs is a pointer to the first element (the pointer you got) and the size of the elements (which is simple in the case of an integral data type like int). With that pointer and an index the retrieval of the target element is simple.

And since the makers of C liked the concept of interchanging things if possible for flexible coding, arrays and pointers could be interchanged at some occasions. Not the golden standard of nice and readable coding, but handy in some circumstances.
0

LVL 34

Expert Comment

ID: 40336362
``````Not the golden standard of nice and readable coding, but handy in some circumstances.
``````
no other language uses the concept and one of the first enhancements c++ added to c was to provide container classes which were a full and safe substitute for the pointer-array mess of c. the idea to turn an array variable to a simple pointer when passing it to a function, is one of the biggest causes for troubles in millions of programs. don't think that there are any efficiency benefits involved by that as for any kind of dynamic arrays you would need to pass array size or number of elements anyhow.

hence, it is good and recommendable praxis - especially for c programmers - to always use a pair of pointer to first element and number of elements when passing arrays to functions where they were turned to pointers or use a structure instead of a plain array.

Sara
0

LVL 12

Assisted Solution

trinitrotoluene earned 126 total points
ID: 40336688
The array name is a pointer to the first element of the array.

when memory is allocated for an array the starting address is fixed and the array name is a sort of alias for the address of the first element.
You cannot change this starting address of the array and that is why you cannot increment or decrement using the array name and it can never be used as a lvalue

``````int arr[100];

arr = 3; //bug
arr++; //bug

arr[0] = 3; //ok

*(arr + 0) = 3; //ok and equivalent to arr[0] = 3;
*(arr + 1) = 34; //equivalent to arr[1] = 34
``````
0

LVL 12

Assisted Solution

trinitrotoluene earned 126 total points
ID: 40336696
here's a good discussion on it written from a C perspective

http://c-faq.com/~scs/cgi-bin/faqcat.cgi?sec=aryptr
0

LVL 32

Assisted Solution

phoffric earned 62 total points
ID: 40336995
In C++ you can pass by reference a non-dynamic array to a function without passing the size of the array into the function. The template function addArray, deduces the size of the array at the compiler stage thereby saving the run-time overhead of having to save the length of a non-dynamic array. Consider this just a heads-up when you get to the chapter on templates.
``````template<int N>
{
int sum = 0;
int i = 0;
int* ptr=array;    // optional - only if you use the *ptr++ approach
for (i = 0, ptr=array; i < N; ++i)
{
//sum += array[i];
sum += *ptr++;   // usually faster than using array[i]
}
return sum;
}

int main()
{
int arrayInt[] = {1,2,3,4,5};
int accum = addArray(arrayInt);
}
``````
0

LVL 14

Assisted Solution

frankhelk earned 187 total points
ID: 40338996
@Sarabande:
You're right in the fact that it's a good idea to have the array size along with the array pointer, and it's much of a help for developers if array bounds are checked whenever an array element is accessed. That reduced much of the possible error sources.

But the creators of C had another paradigma, which was performance and flexibility. The first measure they took was to design the language very close to the logics of machine code, which made the compilation into machine code easy and very efficient. The second measure was to omit almost all safety belts and airbags - if a compiler inserts checks for such things as array bounds, they're inserted over and over again, and that makes programs fat & slow. So they relied on the premisse that the developer always knows what he does. The result is that programs in C are fast and lean, and C allows a lot of tricks that no other language would tolerate, but on the other there are not much languanges that could produce so inspirative code and system crashes. So the developer has to consider more things with C than with other languages. It's like driving a Ferrari (that needs some experience to prevent crashing into the next tree) or an old Volvo (that makes it easy to survive even when you run into the car before you).

I admit that such considerations depend on the type of software to develop - I would never recommend to do end user applications like accounting in C, but it would be a completely different thing when developing low level disk drivers or time critical online data mangling for process control.
0

LVL 34

Assisted Solution

sarabande earned 62 total points
ID: 40340921
Frank, using a pointer instead of an array was due to the little memory space available (stack and heap) in the early c days. a pointer was 16-bit in most environments while a descriptor which is a pair of address and size (as used for strings in fortran) was at least 32-bit and fast grows up to 64-bit to be able to handle more than 64k for buffers. that was a huge difference in those days. efficiency didn't play so much a role then and today because any  function which needs the size of an array would need to get passed this information somehow and techniques like checking for a final zero element (strings) are much less speedy than an additional argument or a pointer to a descriptor instead of a pointer to array. if you put a fixed-sized array into a struct and pass a pointer to struct instead of a pointer to array, you got a simple c equivalent to the template solution phoffric has posted. both alternatives should be as fast and efficient as pointers to array but without the disadvantages.

Sara
0

LVL 14

Assisted Solution

frankhelk earned 187 total points
ID: 40341713
Sara, you're right in the aspect of memory - surely that was much of concern in those days, when RAM and ROM sizes ranged in kB and Bill gates told us that 640 kB ought to be enough for everyone (I remeber that from my TRS80 days, even while I never had a C compiler for it  and those 640 kB were ten times of the address range I had for ROM and RAM together ;-)

But speed was as much a concern in those days - when processor clock ranged in single digit MHz values (My TRS80 had a 1.something MHz Z80 ....). No program with a considerable amount of calculation could spare the CPU cycles for checking the array index against the array size on every access ... in that times. And that was surely one aspect in the design of C.

I admit that today the contemporary memory sizes and processor speeds simply allow language architectures where the developer has not to care about a great amount of thing because the compiler implements all those the checks under the hood of object encapsulation. I'm not sure if that is good in all aspects, because many of the programmers never have learned the techniques for the generation of really efficient code - they  leave it to the compiler optimization of even never think about such things. So the advance in memeory size and processor speed gets eaten up by the growing lazyness of the developers.
0

Author Closing Comment

ID: 40352704
first value to save space on old computers
thanks for historical data also
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

### Suggested Solutions

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, whâ€¦
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a Gâ€¦
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
###### Suggested Courses
Course of the Month5 days, 5 hours left to enroll

#### 738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.