将字符串数组传递给函数

Mik*_*ike 5 c

我试图将一个字符串数组(C样式字符串)传递给一个函数.但是,我不希望在函数的每个字符串的长度上放置最大大小,也不想动态分配数组.这是我先写的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void fun(char *s[])
{
    printf("Entering Fun\n");
    printf("s[1]=%s\n",(char *)s[1]);
}

int main(void)
{
    char myStrings[2][12];

    strcpy(myStrings[0],"7/2/2010");
    strcpy(myStrings[1],"hello");
    fun(myStrings);

    return(0);
}
Run Code Online (Sandbox Code Playgroud)

我在运行时遇到了一个seg错误,并且编译器发出以下警告:stackov.c:在函数'main'中:stackov.c:17:警告:从不兼容的指针类型stackov.c传递'fun'的参数1:5:注意:预期'char**'但参数类型为'char(*)[12]'

但是,当我将main()更改为以下内容时,它可以正常工作:

int main(void)
{
    char myStrings[2][12];
    char *newStrings[2];

    strcpy(myStrings[0],"7/2/2010");
    strcpy(myStrings[1],"hello");
    newStrings[0]=myStrings[0];
    newStrings[1]=myStrings[1];
    fun(newStrings);

    return(0);
}
Run Code Online (Sandbox Code Playgroud)

当数组传递给函数时,数组[2] [12]是否与字符指针数组相同?

Mat*_*hen 7

不,char array[2][12]是一个二维数组(数组数组). char *array[2]是一个指针数组.

char array[2][12] 好像:

7/2/2010\0\x\x\xhello\0\x\x\x\x\x\x
Run Code Online (Sandbox Code Playgroud)

其中\ 0是NUL而\ x是不确定的.

char *array[2] 是:

0x CAFEBABEDEADBEEF
Run Code Online (Sandbox Code Playgroud)

(假设32位)

第一个有24个连续字符,第二个有两个指针(到别处的字符串的开头).