Solved

array of character pointers

Posted on 2006-07-11
7
932 Views
Last Modified: 2012-08-14
Hey, can anyone tell me what is exactly going on when I declare an array of character pointers? how come each index of the array can point to another string?  thanks
0
Comment
Question by:yattias
7 Comments
 
LVL 8

Accepted Solution

by:
manish_regmi earned 25 total points
ID: 17082943
Array of pointers are just arrays containing pointers ie address.
Those address can be a location of the string stored somewhere else.

char *arr[5];

arr[5] gives you the address stored in that array.


regards
Manish Regmi

0
 
LVL 5

Assisted Solution

by:bastibartel
bastibartel earned 25 total points
ID: 17083151
Hi there,

In addition to manish_regmi, who is totally right ..

Maybe you really want to declare a pointer to char (char*  MyStr; /*or*/ char MyStr[10]; )
Then MyStr is what we like to call a 'string' but really just a pointer to a char.

The first declaration does not yet reserve any space for the string and must be allocated using
MyStr = new char[10];   // string length 9 (+1 for terminating '\0' character )

The second declaration reserves 10 char slots right away

Cheers,
Sebastian
0
 
LVL 39

Assisted Solution

by:itsmeandnobodyelse
itsmeandnobodyelse earned 25 total points
ID: 17083234
>>>> how come each index of the array can point to another string?

   // define the array of pointes on the stack
   // and initialize each pointer with NULL
   char* carr[5] = { NULL };

   // allocate (dynamic)storage for each pointer
   // note, each array element might get a different storage or keep NULL
   for (int i = 0; i < sizeof(carr)/sizeof(char*); ++i)
   {
        carr[i] = new char[100];
        // Note, the storage isn't initialized

        // you could terminate the char array by a terminating zero character
        // thus making it an empty string

        carr[i][0] = '\0';

        // or initialize any char element
        for (int j = 0; j < 100; ++j)
              carr[i][j] = '\0';

        // alternatively, you can do the same by calling memset
        memset(carr[i], 0, 100);
   }

   strcpy(carr[0], "Hello");
   strcpy(carr[1], "World");
   ...
 
Generally, you should guarantee that

- a char pointer always points to valid storage or is NULL
- the char array - where the pointer is pointing to the first element -
  is zero-terminated if contains text
- the char array is properly sized if you are writing (copying) to

An alternative to plain C char arrays are string classes, e. g. std::string, which are much easier and much more comfortable.

#include <string>
using namespace std;

      ...
      // creates 5 empty strings
      string strarr[5];
      strarr[0] = "Hello";
      strarr[1] = "World";

Regards, Alex
0
 
LVL 7

Assisted Solution

by:nafis_devlpr
nafis_devlpr earned 25 total points
ID: 17088162
When you declare a char pointer its ready to point to a single or a range of contiguouse characters (ie a character array), so when you declare an array of character pointers it actually contains an array of pointers where each of them are ready to point to a single or a range of contiguouse characters (ie a character array).
For example, if you want to declare an array of strings you can do the following:

char * arr[10]={NULL};
int i=sizeof(arr)/sizeof(arr[0]);

for (--i; i >= 0; --i)
      {
            arr[i]=new char[10];
            arr[i][0]=0;
      }

but you have to delete these allocated memory as they were created in heaps

i=sizeof(arr)/sizeof(arr[0]);

for (--i; i >= 0; --i)
      {
            delete[] arr[i];
            arr[i]=NULL;
      }

although you dont have to delete the arr array as it was craeted in stack

but there is another way in which you can create a resizable array of resizable strings using STL vector and string class

//headers
#include<vector>
#include<string>

using std::vector;
using std::string;

vector<string> str;

for(i=0; i < 10; i++)
      {
               //you can push a string object or c-style string
            str.push_back("Hello");
      }

this approach is much easier and you dont have to think about the alocation of the memory as vector and string will handle those themselves

Nafis
0
 
LVL 13

Assisted Solution

by:marchent
marchent earned 25 total points
ID: 17121905
I guess this little program should give u some idea that u asked for

#include<stdio.h>
#include<string.h>
#define MAX 100

int main()
{
      char p[MAX];
      char q[MAX];
      char *a;
      char *b;
      char *temporary;
      //assign value
      strcpy(p,"Test1");
      strcpy(q,"Test2");
      //show current value of p[] and q[]
      puts(p);      //p pass the parameter as first index of p[]
      puts(q);      //p pass the parameter as first index of p[]
      puts("\n");
      //get the address or p and q
      a = p;
      b = q;
      //show content at address a and b
      puts(a);
      puts(b);
      puts("\n");
      //swap a with b
      temporary = a;
      a = b;
      b = temporary;
      //show content at address a and b after swap
      puts(a);
      puts(b);
      puts("\n");
      return 0;
}
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
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.

856 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