char [length]初始化并处理 [英] char [length] initialization and dealing with it

查看:89
本文介绍了char [length]初始化并处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个char数组:

I have defined a char array:

char d[6];

如果我对以下内容有误,请纠正我:

Correct me if I'm wrong regarding following:

目前,没有为变量 d 分配内存。现在,我要对其进行初始化:

At this moment no memory is allocated for variable d. Now I'm going to initialize it:

d="aaaaa";

这种初始化之后,就不需要释放内存了;

After this kind of initialization, there would be no need to free memory; it will be done automatically.

我怎么知道 char [] 是否已初始化?我正在寻找这样的模式

How do I know if the char[] was initialized? I am looking for a pattern like

if (filled(d)){..}

此外,如何用一种字符填充char []?

Also, how do I fill char[] with one kind of character?

推荐答案


目前,没有为变量d分配内存。

At this moment no memory allocated for variable d.

不正确。

char d[6];

是6个 char s的未初始化数组并且已经为堆栈分配了内存。堆栈变量不需要显式地 free() d,无论它们是否已初始化。当堆栈变量超出范围时,将释放该变量使用的内存。仅通过 malloc() realloc() calloc()应该传递给 free()

is an uninitialised array of 6 chars and memory, on stack, has been allocated for it. Stack variables do not need to be explicitly free()d, whether they are initialised or not. The memory used by a stack variable will be released when it goes out of scope. Only pointers obtained via malloc(), realloc() or calloc() should be passed to free().

要初始化:

char d[6] = "aaaaa"; /* 5 'a's and one null terminator. */

或:

char d[] = "aaaaa"; /* The size of the array is inferred. */

而且,正如 mathematician1975 ,数组分配是非法的:

And, as already noted by mathematician1975, array assignment is illegal:

char d[] = "aaaaa"; /* OK, initialisation. */
d = "aaaaa";        /* !OK, assignment. */

strcpy() strncpy() memcpy() snprintf()等可用于在声明后复制到 d 或将 char 分配给的各个元素d

strcpy(), strncpy(), memcpy(), snprintf(), etc can be used to copy into d after declaration, or assignment of char to individual elements of d.


如何知道char []已初始化?如果填充(d){..}

How to know was char[] initialized? I need pattern if filled(d){..}

如果数组为null终止,则可以使用 strcmp()

If the arrays are null terminated you can use strcmp()

if (0 == strcmp("aaaaaa", d))
{
    /* Filled with 'a's. */
}

或使用 memcmp()如果不是null终止:

or use memcmp() if not null terminated:

if (0 == memcmp("aaaaaa", d, 6))
{
    /* Filled with 'a's. */
}








如何用一种字符填充char []?

How to fill char[] with one kind of characters?

使用 memset()

memset(d, 'a', sizeof(d)); /* WARNING: no null terminator. */

或:

char d[] = { 'a', 'a', 'a', 'a', 'a', 'a' }; /* Again, no null. */

这篇关于char [length]初始化并处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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