2

我在尝试编写分配有以下函数的矩阵的第二行(段错误exc_bad_access和)时遇到问题:kern_invalid_address

这是我的分配函数:

int amatrix(char*** m, const int i, const int j) 
{

    int k;

    (*m) = (char**) malloc(sizeof(char*) * i);
    if ((*m) == NULL) {
        return ERROR;
    }

    for (k = 0; k < i; k++) {
        (*m)[k] = (char*) malloc(sizeof(char) * j);
        if ((*m)[k] == NULL) {
            return ERROR;
        }
    }

    return SUCCESS;
}

我使用以下方法调用它:

char** matrix;
if (amatrix(&matrix, i, j)) { ...

编辑: 根据要求:

#define ERROR 00
#define SUCCESS 01

问题出在的访问:

int gmatrix(char*** m, const int i, const int j)
{
int k, l;

for (k = 0; k < i; k++) {
    for (l = 0; l < j; l++) {
        printf("Matrix[%d][%d] = ", k, l);
        scanf(" %c", m[k][l]);
    }
}

return SUCCESS;
}

感谢您的快速回复!

4

1 回答 1

2

Your gmatrix function should take m as a char** parameter, not char***, because it does not need to change its value like amatrix does (only what it points to).

Then you should change the scanf call to:

scanf(" %c", &m[k][l]);

Your current code (with char*** m) doesn't work because m[k] will give undefined behavior when k!=0, because m points only to a single char**.

If m is a char***, the scanf call would need to look like:

scanf(" %c", &(*m)[k][l]);
于 2012-11-07T14:19:26.307 回答