c - 如何获得 char * 矩阵?

标签 c xcode matrix char

我试图用 C 语言获取 char * 矩阵,但出现运行时错误。以下代码显示了我如何尝试执行此操作。谁能告诉我哪里错了以及为什么?我是 C 编程新手,但我来自 Java 和 PHP 世界。 预先感谢您的关注和帮助

int rows = 10;
int cols = 3;

//I create rows
char *** result = calloc(rows, sizeof(char **));

//I create cols
for (int i = 0; i < cols; i++)
{
    result[i] = calloc(cols, sizeof(char *));
}

//Load values into the matrix
for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < cols; j++)
    {
        result[i][j] = (char *)malloc(100 * sizeof(char));
        if (NULL != result[i][j])
        {
            strcpy(result[i][j], "hello");
        }
    }
    printf("\n");
}

//Print the matrix
for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < cols; j++)
    {
        printf("%s\t", result[i][j]);
    }
    printf("\n");
}

Ps:我正在使用带有 C99 的 xCode

此处发生运行时错误:

result[i][j] = (char *)malloc(100 * sizeof(char));

xCode 返回 EXC_BAD_ACCESS

最佳答案

这个:

for (int i = 0; i < cols; i++)
{
    result[i] = calloc(cols, sizeof(char *));
}

应该是这样的:

// -----------------here
for (int i = 0; i < rows; i++)
{
    result[i] = calloc(cols, sizeof(char *));
}

不相关:Stop casting memory allocation functions in C 。这:

result[i][j] = (char*)malloc(100 * sizeof(char));

应该是这样的:

result[i][j] = malloc(100 * sizeof(char));

我发现这里很奇怪,因为您正确地没有转换您的calloc结果。

<小时/>

替代版本:可变长度数组 (VLA)

如果您的平台支持 VLA,您可以通过利用 VLA 来消除分配循环之一。如果完成,代码将减少为使用单个 calloc 分配整个 char* 矩阵。例如:

int main()
{
    int rows = 10;
    int cols = 3;

    // create rows
    char *(*result)[cols] = calloc(rows, sizeof(*result));

    // load values into the matrix
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            result[i][j] = malloc(100 * sizeof(char));
            if (NULL != result[i][j])
            {
                strcpy(result[i][j], "hello");
            }
        }
        printf("\n");
    }

    //Print the matrix
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            printf("%s\t", result[i][j]);
        }
        printf("\n");
    }
}

关于c - 如何获得 char * 矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26168969/

相关文章:

ios - 将react-native从0.59更新到0.61.4后找不到“React/RCTBundleURLProvider.h”文件

Python、numpy、矩阵

c - 无论标志如何,来自二进制的 fread 返回相同

objective-c - 如何在 Xcode 11 中启动没有 Storyboard >= iOS 13 的新项目?

c - 使用 sendfile(),是否可以判断 in_fd 何时处于 EOF?

ios - 在我的案例中,我需要 iPhone/iPad 特定的按钮图像吗?

c - 动态矩阵作为函数的静态参数

r - 从矩阵创建数据框

c - 为什么 gcc 会创建冗余的汇编代码?

c- 在函数中分配结构成员时出错