Returning 2d array from function?

Hello How can I return a dynamically allocated 2d array from a function?

do I use like this:
1
2
3
4
5
6
7
8
9
10
11
12
int main(){
   char **array;
    array=func();
}
char ** func(){
   
       char** ptr=new char[5]; //five words
        ptr[0]=new char[size of word1];
       *ptr[0]=word1
         ........
      return ptr;
}


Am I rights?
Last edited on
No.
1) Underlying type of ptr is char*. not char. So you should use new char*[5]; (and error message should tell you this.)
2) *ptr[0]=word1 you cannot copy c-strings like that. Use strncpy()
That non commented 8 period ellipsis...
in this am i right

char **array;
array=func();
Yes. You can do that.
thanks, i will code now and chekc, if prob i come back :)
I get error here

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
char ** createArray(char file[]){

    ifstream read;
    char** ptrChar=NULL, word[20];
    int words, i=0;
    read.open(file, ios::in);

    if(!read.is_open()){
        cout<<"Open failed";
        return ptrChar ;
    }

    read>>words;
    cout<<"Number of words in file "<<words<<endl;
    ptrChar=new char*[words];
    cout<<"Size of ptrChar "<<sizeof(ptrChar)<<endl;
    while(read.good()){
        read.getline(word, 20);
        ptrChar[i]=new char[20];
       strcpy(*ptrChar[i], word);//////--here
       cout<<*ptrChar<<endl;
       i++;
    }
Last edited on
ptrChar is a char** 
ptrChar[i] is a char* 
*ptrChar[i] is a char 
strcpy expects char* as first parameter.
Last edited on
done I did like this (*(ptrChar+i), word)..its working
btw I had to add read.clear read.ignore to get first word

:))))
Last edited on
Topic archived. No new replies allowed.