Question:

What are the uses of pointers with respect to arrays and strings in C++?

by  |  earlier

0 LIKES UnLike

Why pointers are often used in string manipulation and arrays. What are their benefits? Please provide examples.

 Tags:

   Report

2 ANSWERS


  1. In C++ to pass a "String" (which is really an array of characters) to another method you have to refer to it's location in memory. Java takes care of the passing for you, but C++ takes a little more manual dirty work.

    It's been a while since I've coded in C/C++, so I don't remember what happens if you don't refer to the passed array not by its address (pointer); basically, pointers are a necessary part of data manipulation in C++.


  2. People use pointers when dealing with arrays because, in C and C++, arrays are really only segments of memory set aside to hold data. The section of memory is a long enough to hold all values consecutively. This means, that when dealing with arrays, one only needs to have the memory address (the pointer) of the first item in that array and the programmer will have access to all of the data in that array. This is very useful for dynamically created arrays multi-dimensional arrays that have a length that is not known until runtime. If you try and compile code and pass an int arrayName[][] as a parameter, then you will have problems, because the compiler will want to know one of the dimensions before compiling. However, by passing int **arrayName, then you will get around that problem. Here is a quick code example:

    #include <iostream>

    #include <stdlib.h>

    using namespace std;

    void changeArrayValues(int **arrayOfNbrs, int length);

    int main(int argc, char **argv)

    {

        if (argc < 2){

           cout << "Include a number larger than 0 as a parameter." << endl;

           return -1;

        }  

        int length = atoi(argv[1]);

         if (length < 1){

           cout << "Include a number larger than 0 as a parameter." << endl;

           return -1;

        }

        int **arrayOfNbrs = new int*[length];

        for( int i = 0; i < length; i++)

    arrayOfNbrs[i] = new int[length];

        changeArrayValues(arrayOfNbrs, length);

    for( int i = 0; i < length; i++){

    for( int j = 0; j < length; j++)

    cout << arrayOfNbrs[i][j] << ", ";

    cout << endl;

    }

        for( int i = 0; i < length; i++)

    delete arrayOfNbrs[i];

        delete arrayOfNbrs;

        return 0;

    }

    void changeArrayValues(int **arrayOfNbrs, int len)

    {

         for( int i = 0; i < len; i++)

    for( int j = 0; j < len; j++)

    arrayOfNbrs[i][j] = i * j;    

    }

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.