Solved

integerArray is a pointer

Posted on 2014-09-21
10
157 Views
Last Modified: 2014-09-30
// 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;
}

Open in new window


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)
why is this always the first value (3 in this example)
0
Comment
Question by:rgb192
  • 3
  • 2
  • 2
  • +3
10 Comments
 
LVL 25

Accepted Solution

by:
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 13

Assisted Solution

by:frankhelk
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 32

Expert Comment

by:sarabande
ID: 40336362
Not the golden standard of nice and readable coding, but handy in some circumstances. 

Open in new window

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

by:trinitrotoluene
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

Open in new window

0
 
LVL 12

Assisted Solution

by:trinitrotoluene
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
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 32

Assisted Solution

by:phoffric
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 addArray(int (&array)[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);
}

Open in new window

0
 
LVL 13

Assisted Solution

by:frankhelk
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 32

Assisted Solution

by:sarabande
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 13

Assisted Solution

by:frankhelk
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

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

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
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 how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

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

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

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now