1

这是我的代码:

void doSomething(){
    char arr[5][10];
    arr[1] = "Bob";
    arr[2] = "Steve";
    arr[3] = "Tim";
    arr[4] = "Ruth";
    arr[5] = "Heather";
    init(arr);

void init(char *array){
    int i;
    newArr[5][10];
    for(i=0; i<5; i++){
        newArr[i] = *(array + i);
    }
}

我不断收到错误消息:

警告:从不兼容的指针类型传递 'init' 的参数 1 [默认启用] 注意:预期的 'char ' 但参数的类型是 'char ( )[10]'</p>

4

3 回答 3

4

Your data is a 2-dimensional array, so your function needs to take an array of pointers account for this (i.e. char (*array)[10] or char array[][10]).

Also, in your init function, you can't just copy the strings in to arrays, you either need to copy all the data (as strings with a strcpy or character by character with a second loop) or just copy the pointers to the strings (so make your newArr variable a char *newArr[5]).

If none of this makes any sense, then you should probably brush up on your C Pointer knowledge by reading through the C FAQ on this topic.

于 2012-10-24T19:47:09.093 回答
2

1)在C语言中没有字符数组赋值,strcpy()数组从0而不是1开始:

#include <string.h>
void doSomething(){
    char arr[5][10];
    strcpy(arr[0], "Bob");
    strcpy(arr[1], "Steve");
    strcpy(arr[2], "Tim");
    strcpy(arr[3], "Ruth");
    strcpy(arr[4], "Heather");
    init(arr);
}

2)init()获取一个指向 char 数组的指针;newArr[][]未声明,添加char. init()在源代码的开头添加声明。最后但并非最不重要的一点:再次用strcpy().

void init(char (*array)[10]);

void doSomething() {...}

void init(char (*array)[10]){
    int i;
    char newArr[5][10];
    for(i=0; i<5; i++){
        strcpy(newArr[i], array[i]);
    }
}

最后,这可能很无聊,但请查看https://stackoverflow.com/tags/c/infoC 常见问题解答并拿起一本书。这将为您提供比我更好和更长的服务。

于 2012-10-24T19:50:53.340 回答
-1

那不是错误。它是一个警告。如您所见,您arr在 doSomething 中是一个双数组(可以使用双指针表示),但在 init 中您只使用一个指针。将其更改为双指针**arrayarray[][]*

于 2012-10-24T19:45:31.310 回答