C语言 初始化 char 类型的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6200667/
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 08:49:15  来源:igfitidea点击:

Initializing arrays of type char

carrayspointerschar

提问by matcheek

I want to initialize arbitrary large strings. It is null terminated string of characters, but I cannot print its content. Can anybody tell me why?

我想初始化任意大字符串。它是以空字符结尾的字符串,但我无法打印其内容。谁能告诉我为什么?

char* b;
char c;
b = &c;
*b = 'm';
*(b+1) = 'o';
*(b+2) = 'j';
*(b+3) = 'a';
*(b+4) = '
const char *str1 = "moja";
'; printf("%s\n", *b);

回答by Oliver Charlesworth

Your solution invokes undefined behaviour, because *(b+1)etc. are outside the bounds of the stack variable c. So when you write to them, you're writing all over memory that you don't own, which can cause all sorts of corruption. Also, you need to printf("%s\n", b)(printfexpects a pointer for %s).

您的解决方案会调用未定义的行为,因为*(b+1)等超出了堆栈变量的范围c。因此,当您写信给他们时,您正在写遍您不拥有的内存,这可能会导致各种损坏。此外,您需要printf("%s\n", b)printf需要一个指针%s)。

The solution depends on what you want to do. You can initialize a pointer to a string literal:

解决方案取决于您想要做什么。您可以初始化指向字符串文字的指针:

char str2[] = "moja";

You can initialize a character array:

您可以初始化一个字符数组:

char str2[] = { 'm', 'o', 'j', 'a', '
char *str3 = malloc(5);
str3[0] = 'm';
str3[1] = 'o';
str3[2] = 'j';
str3[3] = 'a';
str3[4] = '
char *b;
char c[5];
b = &c[0];
*b = 'm';
... //rest of your code
'; ... free(str3);
' };

This can also be written as:

这也可以写成:

char * b = (char*) malloc(5);
*b = 'm';
... // rest of your code

Or you can manually assign the values of your string:

或者您可以手动分配字符串的值:

char c[] = "hello";
const char* b = "abcdef";

回答by Pavan Manjunath

This might result in a segmentation fault! *(b+1), *(b+2) etc refer to unallocated areas. First allocate memory and then write into it!

这可能会导致分段错误!*(b+1)、*(b+2) 等指的是未分配的区域。先分配内存,再写入!

回答by N.R.S.Sowrabh

bdoesn't have enough space to hold all those characters. Allocate enough space using mallocor declare bas a chararray.

b没有足够的空间来容纳所有这些字符。使用malloc或声明bchar数组分配足够的空间。

回答by Diego Sevilla

You need to assign memory space for it, either with mallocor using a static array. Here, in your code, you're using the address of just one character to store at the addresses of that characters, andothers following it. This is not defined.

您需要使用malloc或使用静态数组为其分配内存空间。在这里,在您的代码中,您仅使用一个字符的地址来存储该字符的地址,以及其他跟随它的地址。这个没有定义。

Note, step by step, what you're doing. First, you assign the pointer to point to a single char space in memory. Then, by using *b = 'm'you set that memory to the character 'm'. But then, you access to the next memory position (that is undefined, because no memory is reserved for that position) to store another value. This won't work.

注意,一步一步,你在做什么。首先,您将指针分配为指向内存中的单个字符空间。然后,通过使用*b = 'm'您将该内存设置为字符“m”。但是随后,您访问下一个内存位置(未定义,因为没有为该位置保留内存)以存储另一个值。这行不通。

How to do it?

怎么做?

You have two options. For example:

你有两个选择。例如:

printf("%c\n", *b);

This will work because you have space for 5 chars in c. The other option is to directly assign memory for busing malloc:

这将起作用,因为您有 5 个字符的空间c。另一种选择是直接为busing分配内存malloc

printf("%s\n", *b);

Finally, maybe not what you want, but you can either initialize a char array or pointer using a string literal:

最后,也许不是您想要的,但您可以使用字符串文字初始化字符数组或指针:

printf("%s\n", b);

回答by Ozair Kafray

If you write the following instead of your printf, it will print the first character.

如果您编写以下内容而不是 printf,它将打印第一个字符。

##代码##

In order for you to have arbitrarily large strings, you will need to use a library such as bstringor write one of your own.

为了让您拥有任意大的字符串,您需要使用诸如bstring 之类的库或自己编写一个库。

This is because, in C one needs to get memory, use it and free it accordingly. bin your case only points to a character unless you allocate memory to it using malloc. And for mallocyou have to specify a fixed size.

这是因为,在 C 中,需要获取内存,使用它并相应地释放它。b在您的情况下仅指向一个字符,除非您使用malloc. 并且malloc你必须指定一个固定的大小。

For arbitrarily large string, you need to encapsulate the actual pointer to character in a data structure of your own, and then manage its size according to the length of the string that is to be set as its value.

对于任意大的字符串,您需要将实际指向字符的指针封装在自己的数据结构中,然后根据要设置为其值的字符串的长度来管理其大小。

回答by king_nak

Your code is not safe at all! You allocate only 1 char on the stack with char c;but write 5 chars into it! this will give you a stack-overflow which can be very dangerous.

您的代码根本不安全!您在堆栈上只分配了 1 个字符,char c;但向其中写入了 5 个字符!这会给你一个堆栈溢出,这可能是非常危险的。

Another thing: you mustn't dereference the string when printing it: printf("%s\n", b);

另一件事:打印时不能取消引用字符串: printf("%s\n", b);

Why not simply write const char *b = "mojo";?

为什么不简单地写const char *b = "mojo";

回答by Gangnus

##代码##

why *?

为什么 *?

##代码##

is what you want

是你想要的

回答by garph0

The printf does not print because it expect a char*, so you should pass b, not *b. To initialize a pointer to a string constant you can do something like:

printf 不打印,因为它需要一个 char*,所以你应该传递 b,而不是 *b。要初始化指向字符串常量的指针,您可以执行以下操作:

char *s1 = "A string"

char *s1 = "A string"

or

或者

char s2[] = "Another string"

char s2[] = "Another string"

or allocate a buffer with char *b = malloc(5)and then write to this buffer (as you did, or with the string functions)

或分配一个缓冲区,char *b = malloc(5)然后写入该缓冲区(如您所做的,或使用字符串函数)

what you did was taking the address of a single char memory location and then write past to it, possibly overwriting other variables or instructions and thus possibly leading to data corruption or crash.

您所做的是获取单个字符内存位置的地址,然后写入过去,可能会覆盖其他变量或指令,从而可能导致数据损坏或崩溃。