通过多维数组用C [英] Passing multi-dimensional arrays in C

查看:135
本文介绍了通过多维数组用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习C和我来,我一直未能解决的问题。

I am currently trying to learn C and I have come to a problem that I've been unable to solve.

考虑:

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

#define ELEMENTS 5

void make(char **array, int *array_size) {
    int i;
    char *t = "Hello, World!";

    array = malloc(ELEMENTS * sizeof(char *));

    for (i = 0; i < ELEMENTS; ++i) {
    	array[i] = malloc(strlen(t) + 1 * sizeof(char));
    	array[i] = strdup(t);
    }
}

int main(int argc, char **argv) {
    char **array;
    int size;
    int i;

    make(array, &size);

    for (i = 0; i < size; ++i) {
    	printf("%s\n", array[i]);
    }

    return 0;
}

我不知道为什么上面的失败创建后读回数组的内容。我从字面上花了一个小时试图弄清失败的原因,但都拿出了两手空空。毫无疑问,这是一些小事。

I have no idea why the above fails to read back the contents of the array after creating it. I have literally spent an hour trying to understand why it fails but have come up empty handed. No doubt it's something trivial.

干杯,

推荐答案

下面是工作code:

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

#define ELEMENTS 5

void make(char ***array) {
    char *t = "Hello, World!";

    *array = malloc(ELEMENTS * sizeof(char *));

    int i;
    for (i = 0; i < ELEMENTS; ++i) {
        (*array)[i] = strdup(t);
    }
}

int main(int argc, char **argv) {
    char **array;
    make(&array);

    int i;
    for (i = 0; i < ELEMENTS; ++i) {
        printf("%s\n", array[i]);
        free(array[i]);
    }
    free(array);
    return 0;
}

至于其他已经公布 - 有未使用的大小,通过的strdup自行分配内存,并且它是好的,后来释放内存...

As the other have posted - there was unused size, and strdup allocates memory by itself, and it is nice to free the memory afterwards...

这篇关于通过多维数组用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆