C 2d数组无法从int*转换为int

C 2d数组无法从int*转换为int,c,arrays,pointers,malloc,multidimensional-array,C,Arrays,Pointers,Malloc,Multidimensional Array,我试图给C中的2d int数组赋值 int **worldMap; 我想将每一行分配给数组,因此我在循环中执行此操作: worldMap[0][sprCount] = split(tmp.c_str(), delim); sprCount++; 问题是我得到一个错误,上面一行说不能将int*转换为int 以下是创建二维阵列的代码: int** Array2D(int arraySizeX, int arraySizeY) { int** theArray; theArray

我试图给C中的2d int数组赋值

int **worldMap;
我想将每一行分配给数组,因此我在循环中执行此操作:

worldMap[0][sprCount] = split(tmp.c_str(), delim);
sprCount++;
问题是我得到一个错误,上面一行说不能将int*转换为int

以下是创建二维阵列的代码:

int** Array2D(int arraySizeX, int arraySizeY)
{
    int** theArray;
    theArray = (int**) malloc(arraySizeX*sizeof(int*));
    for (int i = 0; i < arraySizeX; i++)
        theArray[i] = (int*) malloc(arraySizeY*sizeof(int));
    return theArray;
}

int**worldMap不是2D数组,不要试图将其视为一个数组。另外,.Short版本:我想你需要
worldMap[sprCount]
。长版本:
worldMap
是指向指针的指针,并分配了一个动态指针数组。使用
worldMap[0]
解除对它的引用可以访问该插槽处的指针,该插槽是一个
int*
表示
int
的动态数组。使用
[sprCount]
解除对该值的引用将导致插槽
sprCount
中的
int
左值。这就是你的错误。
int
不是
int*
。如果要在指针数组中使用
sprCount
行,请使用
worldMap[sprCount]
。(还有一个很好的警告,释放那个插槽的老占用者,否则你会像筛子漏水一样漏掉内存。)
tmp.c_str()
?这通常是C++的一部分……您的<代码> SPLIT()/Case>函数应该简单地返回<代码> int <代码>,不要分配和返回<代码> int */COD>。您已经为数组中的
int
分配了空间。或者,在
Array2d()
函数中不需要第二级分配,分配应该是
worldMap[sprCount]=split(…)
@JonathanLeffler,这看起来像是一个非常谨慎的行创建函数。我认为在
Array2D
中填充不确定值的原始行分配可能是更好的选择。在没有真实背景的情况下难以启齿。
int* split(const char* str, const char* delim)
{
    char* tok;
    int* result;
    int count = 0;
    tok = strtok((char*)str, delim);
    while (tok != NULL)
    {
        count++;
        tok = strtok(NULL, delim);
    }

    result = (int*)malloc(sizeof(int) * count);

    count = 0;
    tok = strtok((char*)str, delim);
    while (tok != NULL)
    {
        result[count] = atoi(tok);
        count++;
        tok = strtok(NULL, delim);
    }
    return result;
}