Sep 18, 2014 at 3:21am UTC
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 Sep 18, 2014 at 3:40am UTC
Sep 18, 2014 at 3:49am UTC
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()
Sep 18, 2014 at 3:57am UTC
That non commented 8 period ellipsis...
Sep 18, 2014 at 6:04pm UTC
in this am i right
char **array;
array=func();
Sep 18, 2014 at 6:34pm UTC
thanks, i will code now and chekc, if prob i come back :)
Sep 18, 2014 at 6:49pm UTC
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 Sep 18, 2014 at 6:50pm UTC
Sep 18, 2014 at 6:56pm UTC
ptrChar
is a char **
ptrChar[i]
is a char *
*ptrChar[i]
is a char
strcpy
expects char *
as first parameter.
Last edited on Sep 18, 2014 at 6:56pm UTC
Sep 18, 2014 at 7:09pm UTC
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 Sep 18, 2014 at 7:12pm UTC