C语言 在 C 中初始化二维字符数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26941470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:33:27  来源:igfitidea点击:

Initializing 2D char array in C

carraysinitialization

提问by mallux

Similar to this question: 2d array, using calloc in C

类似于这个问题:2d array, using calloc in C

I need help initializing a 2D char array that will all be initialized to some value (in this case '0'). I have tried many different methods and I am pulling my hair out. Please let me know what I am doing wrong. This code doesn't work. Thanks!

我需要帮助初始化一个 2D 字符数组,该数组将全部初始化为某个值(在本例中为“0”)。我尝试了很多不同的方法,我正在拔头发。请让我知道我做错了什么。此代码不起作用。谢谢!

char** init_array() {
        char newarray[5][10];
        int i, j;
        for (i = 0; i < 5; i++) {
                for (j = 0; j < 10; j++) {
                        newarray[i][j] = '0';
                }
        }
        return newarray;
}
char **array = init_array();

The errors I get from gcc when I try to compile:

我尝试编译时从 gcc 得到的错误:

test.c: In function ‘init_array':
test.c:12:2: warning: return from incompatible pointer type [enabled by default]
  return newarray;
  ^
test.c:12:2: warning: function returns address of local variable [-Wreturn-local-addr]
test.c: At top level:
test.c:14:1: error: initializer element is not constant
 char **array = init_array();

Should it be like this?

应该是这样吗?

char newarray[5][10];
char** init_array() {
        int i, j;
        for (i = 0; i < 5; i++) {
                for (j = 0; j < 10; j++) {
                        newarray[i][j] = '0';
                }
        }
        return newarray;
}
char **array = init_array();

回答by Mike Dunlavey

I think pictures help. Here is char newarray[5][10]. It is a single memory block consisting of an array of 10 characters, and an array of five of those. You could just clear it with a single memsetcall.

我认为图片有帮助。这是char newarray[5][10]。它是一个单一的内存块,由一个 10 个字符的数组和一个包含 5 个字符的数组组成。你只需一个memset电话就可以清除它。

enter image description here

在此处输入图片说明

Here is char **array. It says arrayis a pointer. What is it a pointer to? a pointer to a character.

这是char **array。它说array是一个指针。它是什么指针?指向字符的指针。

enter image description here

在此处输入图片说明

Keep in mind pointer arithmetic. If arrayis a pointer that happens to point to a pointer, then (*array)equals array[0], and that is the pointer that arraypoints to.

请记住指针算法。如果array是恰好指向某个指针的指针,则(*array)等于array[0],即指向的指针array

What is array[1]? It is the second pointerin the array that arraypoints to.

什么是array[1]?它是指向数组中的第二个指针array

What is array[0][0]? It is the first character pointed at by the first pointer that arraypoints to.

什么是array[0][0]?它是指向的第一个指针所array指向的第一个字符。

What is array[i][j]? It is the jth character of the ith pointer that arraypoints to.

什么是array[i][j]?它是指向的第i个指针的第j个字符。array

So how are newarrayand arrayrelated?
Simple. newarray[i][j]is the jth character of the ith subarray of newarray.

那么如何newarrayarray相关呢?
简单的。 newarray[i][j]是 的第i个子数组的第j个字符。newarray

So in that sense, it's just like array, but without all the pointers underneath.

所以从这个意义上说,它就像array,但没有下面的所有指针。

What's the difference? Well, the disadvantage of arrayis you have to build it up, piece by piece. OTOH, the advantage is you can make it as big as you want when you build it up. It doesn't have to live within a fixed size known in advance.

有什么不同?嗯,缺点array是你必须一点一点地建立它。OTOH,优点是您可以在构建时将其放大到您想要的大小。它不必生活在预先知道的固定大小内。

Clear as mud?

清如泥?

回答by David C. Rankin

Per our discussion in the comments, here is a quick example of zeroing array values at the time of declaration. Note, the values are #definedas constants:

根据我们在评论中的讨论,这里有一个在声明时将数组值归零的快速示例。请注意,这些值是#defined常量:

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

#define MAXSTR 10
#define MAXLEN 1024

int main () {

    char myarray[MAXSTR][MAXLEN] = {{0}};  /* declare a static array of MAXSTR x MAXLEN */

    /* copy various strings to statically declared storage */
    strncpy (myarray[0],"  This is the first string", strlen("  This is the first string")+1);
    strncpy (myarray[1],"  This is the second string", strlen("  This is the second string")+1);
    strncpy (myarray[2],"  This is the third string", strlen("  This is the third string")+1);
    strncpy (myarray[3],"  This is the fourth string", strlen("  This is the fourth string")+1);
    strncpy (myarray[4],"  This is the fifth string", strlen("  This is the fifth string")+1);

    int i = 0;

    /* print the values */
    while (*myarray[i])
        printf ("  %s\n", myarray[i++]);

    return 0;
}

output:

输出:

$ ./myar
    This is the first string
    This is the second string
    This is the third string
    This is the fourth string
    This is the fifth string

build:

建造:

gcc -Wall -Wextra -o myar myarray.c

回答by twasbrillig

To avoid using a global (like the second sample code pasted above) and to avoid using malloc, you can define the array outside your function and pass it in, like this. You don't need to return anything because the array data itself is being modified. Notice that it's necessary to define the array's secondary dimension in the function signature:

为避免使用全局malloc变量(如上面粘贴的第二个示例代码)并避免使用,您可以在函数外部定义数组并将其传入,如下所示。您不需要返回任何内容,因为数组数据本身正在被修改。请注意,有必要在函数签名中定义数组的二级维度:

void init_array(char ary[][10]) {
    int i, j;
    for (i = 0; i < 5; i++) {
        for (j = 0; j < 10; j++) {
                ary[i][j] = '0';
        }
    }
}

int main(void)
{
    char newarray[5][10];
    init_array(newarray);
    printf("%c", newarray[1][1]); /* Testing the output */
    return 0;
}

That returns '0'.

那返回'0'。

http://codepad.org/JbykYcyF

http://codepad.org/JbykYcyF