2

i had a little problem trying to pass the address for a character array to a function, here is a simple example of what i am trying to do :

char a[20] = {"hello"};
printit( &a );

can you please give me the declaration of he printit function ( and maybe why ), i was expecting something like :

void printit( char ** value );
or void printit( char * value[] );

to work, but it is not.

*Error messages :

void printit( char ** value ); => cannot convert parameter 1 from 'char (*)[20]' to 'char **'
void printit( char * value[] ); => cannot convert parameter 1 from 'char (*)[20]' to 'char *[]'

thanks in advance.

Regards, max.

5
  • What was the problem? (The error message) Commented Jun 11, 2013 at 9:21
  • Just telling us that it didn't work is not helpful. You need to tell us exactly what you tried, exactly what you expected it to do, and exactly what happened. Commented Jun 11, 2013 at 9:22
  • i have added the error message for each declaration. Commented Jun 11, 2013 at 9:25
  • For a print function of a string, the only declaration that makes sense is this: void printit (const char* str);. It is not clear to me whether printit is your own user-defined function or part of a library, however. Commented Jun 11, 2013 at 9:28
  • @Max Maybe you wanted this. Check out the selected answer. &t is a pointer to the array as whole, hence int (*)[10] Commented Jun 11, 2013 at 11:50

2 Answers 2

7

Your parameter &a is a pointer to an array of 20 chars, hence:

void printit(char (*value)[20]);  // value is a pointer to an array of 20 chars

.

However, more commonly (especially with strings) would be to change the call into

printit(a);   // a will be passed as pointer to first elelemt, i.e. 'a' can be used as pointer to char

and define printit as

void printit(char *value)
{
     printf("The string is: %s", value);
}
Sign up to request clarification or add additional context in comments.

2 Comments

as i understand , char a[2];// a is a pointer to the beginning of the array , so why do i have to give the size in the function declaration, and is there a way to pass it without the [20]
if you just pass 'a' as the parameter (as in my 2nd example) you can use it like a pointer to the first element of the array. If you pass &a you need the [20].
1

*Edited .. made a mistake

You are not declaring an array of char* you are declaring an array of char. Adding asterisk to your variable declaration and removing the & should make it work:

void printit(char** arr){
  string tmp(arr[0]);
  cout<<tmp<<endl;
}


char* a[20] = {"hello"};
printit( a );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.