Passing char* argv[] from main

May 25, 2013 at 6:37am
How would I pass a char pointer to a array of pointers to a function? (think i said that right) I want to print out the strings from the command line arguments but this prints only the first char. seems like im dealing with a multidimensional array... im confused..


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  #include <iostream>


using namespace std;

void cstring(char *x[], int z);



int main(int argCnt, char * charArray[])
{

cstring(charArray,argCnt);


}

void cstring(char *x[],int z){
    for(int i = 0;i != z; ++i)
        cout << *x[i] << endl;
}
Last edited on May 25, 2013 at 7:38am
May 25, 2013 at 7:06am
hi.
there seems to be one flaw from the outside:
in line 20, the expression you're using is a three level pointer.
your writing is the same as:
 
cout<<***(x+i)<<endl;

that should explain it.


try using
 
cout<<x[i]<<endl;
May 25, 2013 at 7:11am
1
2
3
4
void cstring(char *x[],int z){
    for(int i = 0;i != z; ++i)
        cout << x[i] << endl;
}
May 25, 2013 at 7:33am
thanks! i got it however if its a pointer, why doesnt it need to be dereferenced?


cout<<***(x+i)<<endl;
this gave error:
|20|error: invalid type argument of unary '*' (have 'char')|
Last edited on May 25, 2013 at 7:36am
May 25, 2013 at 7:42am
its type is char**
when we use subscript operator x[i] we gor char*, which is c-string. And << operator have overload which supports x-strings.
Compare:
1
2
3
4
5
6
const char* a = "Hello";
std::cout << a;

const char* b[] = {"hello", "world", "!"};
for (int i = 0; i < 3; +++i)
    std::cout << b[i] << std::endl;
Topic archived. No new replies allowed.