Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass char array as argument

Can anyone explain to me what I don't understand here please?

I am trying to pass the argument as a "string" (i know there are no strings in c) so that I can use that string later with other functions like it's a file name that has to be passed for example. But I don't know why it won't accept it or what type should it be

#include <stdio.h>

int main ( int argc, char *argv[] )
{
    char *array= argv[0];
    foo(*array);
}

void foo( char *array) 
// notice the return type - it's a pointer
{
    printf(array);
}

thanks alot!

like image 283
Ryan Avatar asked Jul 30 '12 01:07

Ryan


1 Answers

You should be calling the function like this:

foo(array);

What you're doing is dereferencing the pointer, which returns a char, which is the first character in the string.

Your printf call should also look like this:

printf("%s", array);

Your entire fixed code should look like the following:

#include <stdio.h>

void foo(char *array)
{
    printf("%s", array);
}

int main ( int argc, char *argv[] )
{
    // TODO:  make sure argv[1] exists
    char *array= argv[1];
    foo(array);
}
like image 54
Tim Cooper Avatar answered Oct 09 '22 03:10

Tim Cooper