Solved

array of character pointers

Posted on 2006-07-11
7
927 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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
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 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.

705 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

18 Experts available now in Live!

Get 1:1 Help Now