-1

我是 C 和指针的新手,我想知道是否可以将数组指针传递给函数而不是传递字符数组本身。我正在发布代码中的片段。

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.
}
4

2 回答 2

1

数组在 C 中总是通过指针传递,而不是通过值传递(复制)

所以

int runCommand (char x[24]);

非常接近

int runCommand (char *x);
于 2013-10-29T15:39:08.230 回答
0

是的,可以将指向数组的指针传递给函数。不,这可能不是你想要的。

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));
}

x就是指向 24 个字符的数组的指针。不过要非常小心。通常,您不想将指针传递给数组;你只想传递指针。

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));
}
于 2013-10-29T15:43:50.683 回答