简体   繁体   English

分配2D字符数组

[英]Allocating a 2D array of characters

I am making a program to allocate a 20x20 array of characters. 我正在制作一个分配20x20字符数组的程序。 Here is what I did: 这是我做的:

#include<stdio.h>
#include<stdlib.h>
int main()
{
char *a=(char*) calloc(20,sizeof(char[20]));
a[0]="abcd";
printf("%s\n",a[0]);
return 0;
}

Link to ideone . 链接到ideone

The output of the above code is (null) . 上面代码的输出是(null) Can anybody please explain this? 有人可以解释一下吗? According to me, I am allocating a pointer a 20 spaces of size 20 each. 据我说,我正在分配a 20个大小a 20的空格。 So a[0] technically has enough memory to store "abcd", yet the output is null . 所以a[0]技术上有足够的内存来存储“abcd”,但输出为null

The type of variable a that you have is incorrect: it should be char (*a)[20] (yes, with parentheses). 你拥有的变量a的类型是不正确的:它应该是char (*a)[20] (是的,带圆括号)。

This line is also incorrect: 这一行也是错误的:

a[0]="abcd";

you cannot assign C strings like that, because a[0] is not a pointer: it is an array of 20 characters, so you need to use strcpy instead: 你不能像这样分配C字符串,因为a[0]不是指针:它是一个20个字符的数组,所以你需要使用strcpy

#include<stdio.h>
#include<stdlib.h>
int main()
{
    char (*a)[20]=calloc(20, sizeof(char[20]));
    strcpy(a[0], "abcd");
    strcpy(a[1], "wxyz");
    printf("%s\n",a[0]);
    printf("%s\n",a[1]);
    return 0;
}

See the corrected program running here . 查看此处运行的更正程序。

Note: Unlike C++, C does not require type casting of void pointers. 注意:与C ++不同,C不需要对void指针进行类型转换。 It is typical for C programs to omit the cast of results returned from malloc , calloc , and realloc , because the type is already known from the type of the variable being assigned. C程序通常省略从malloccallocrealloc返回的结果的转换,因为已从所分配的变量的类型中知道该类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM