array of pointers

How do i fill in the array of pointers with strings without using dynamic memory allocation? I start to begin thinking that i won't be able to find a way to do it, because of the elements of the array being pointer constants >.<

 
  char *array_ptr[10]={0}; // i do not ask this-> *array_ptr[]={"blabla","more"....} 


1
2
3
4
5
//I understand that the following method to fill in the array is wrong:
char *array_ptr[10]={0};
int i;
for(i=0; i<10; i++)
    scanf("%s",array_ptr[i]); //i think it does also not work using all other data input functions ,fgets,sscanf etc etc 

Last edited on
How do i fill in the array of pointers with strings without using dynamic memory allocation?

Have you considered just using a normal statically allocated array?

1
2
3
char names[10][100];
for(int i = 0; i < 10; ++i)
   scanf("%99s", names[i]);
yes sir/madam i have. I just wonder if it possible to do that using a pointer array,it is an overstretch,but i am thinking it through for several hours if i could come up with something only to come to the conclusion that there is very likely no way to do it...
Why do you want to use a pointer array? The memory for those strings need to be allocated somewhere.

experimental purposes, to get a better feel of the language.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

int main()
{
    const std::size_t num_strings = 10;
    const std::size_t max_len = 100;

    // some storage to work with
    char buffer[num_strings * max_len];

    // point the array of pointers to the storage.
    char* ptrs[num_strings];
    for (std::size_t i = 0; i < num_strings; ++i)
        ptrs[i] = buffer + i*max_len;

    // get and store strings..
    for (std::size_t i = 0; i < num_strings; ++i)
        std::cin.getline(ptrs[i], max_len);
}
Topic archived. No new replies allowed.