-1

I am new to C and pointers and I'd like know if its possible to pass an array pointer to a function instead of passing the array of characters itself. I am posting the snippet from the code.

char ipAddress[24];
int i, j;
for (i = 12; i <= 13; i++)
{
    for (j = 1; j <= 254; j++)
    {
        sprintf(ipAddress,"192.168.%d.%d",i,j);
        runCommand(ipAddress);
    }
}

// ...

int runCommand (char x[24])
{
    // Do stuff.
}
3
  • 2
    This already passes a pointer.
    – Fred Foo
    Oct 29, 2013 at 15:36
  • You need to specify your problem.
    – zoska
    Oct 29, 2013 at 15:39
  • The array name is always a pointer to the first element of the array Oct 29, 2013 at 15:42

2 Answers 2

1

Arrays are always passed by pointer in C, not passed by value (copyed)

So

int runCommand (char x[24]);

is close equivalent of

int runCommand (char *x);
3
  • -1: Inside the function runCommand(char x[24]), the value of sizeof(x) is sizeof(void *) and not 24. Try it and see. Ping me a comment when you've fixed this. Oct 29, 2013 at 15:46
  • @JonathanLeffler Yes! Strange, but true. No matter compiler sees real type with size it continues emulating char* to the end. Oct 29, 2013 at 15:56
  • Since my background is basically from Perl,i was thiking more in terms of passing an array reference to a function & deref it later in the function,than passing the array itself..i.ee pass-by-reference not pass-by-value.So,if i am to understand,from my above code,Arrays are always passed by pointer in C to a function,right ?
    – hmmm
    Oct 30, 2013 at 6:28
0

Yes, it is possible to pass a pointer to an array to a function. No, it is probably not what you want.

int runCommand(char (*x)[24])
{
    if ((*x)[0] == '\0')  // Option 1
        return -1;
    if (x[0][0] == '\0')  // Option 2: equivalent to option 1.
        return -1;
    ...
}

void alternative(void)
{
    char y[24] = "Samizdat";
    printf("%d\n", runCommand(&y));
}

That says x is a pointer to an array of 24 characters. Be very careful, though. In general, you do not want to pass a pointer to an array; you just want to pass pointers around.

int runCommand(char x[24])  // Or: char *x
{
    if (x[0] == '\0')  // Option 1
        return -1;
    ...
}

void alternative(void)
{
    char y[24] = "Samizdat";
    printf("%d\n", runCommand(y));
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.