gpt4 book ai didi

c - 如何定义字符串数组的结尾

转载 作者:太空狗 更新时间:2023-10-29 15:19:32 26 4
gpt4 key购买 nike

char 数组变满之前结束它的一种方法是将 '\0' 放在末尾,例如-

single_str[5] ='\0';

那么如何结束一个二维char数组呢?

最佳答案

在实践中,您应该在 C 中避免考虑二维数组。严格意义上,C 语言不了解二维数组,只了解数组的数组(固定长度,所有大小相同)或指针数组(或聚合数组或标量数组)。

您可以使用字符串指针数组。 C 字符串通常以零字节结尾。下面是一个以 NULL 字符串结尾的常量数组(常量字符串,即 const char* 指针)的示例

const char*const arrstr[] = {
"Hello",
"Nice",
"World",
NULL
};

在我的机器上,sizeof(const char*) 是 8,所以 sizeof(arrstr) 是 32; sizeof("Nice") 为 5。

你可以打印所有的数组成员

for (const char*const* p = arrstr; *p; p++) printf("%s\n", *p);

您可以在 C99 中使用以 flexible array member 结尾的结构,例如

struct my_string_array_st {
unsigned len;
char* arr[]; // array of len pointers */
};

那么你可能有一个构造函数来构建这样的空内容字符串数组

struct my_string_array_st* make_string_array(unsigned ln) {
struct my_string_array_st*p
= malloc(sizeof(struct my_string_array_st) + len*sizeof(char*));
if (!p) { perror("malloc"); exit(EXIT_FAILURE); };
p->len = ln;
for (unsigned ix=0; ix<ln; ix+) p->arr[ix] = NULL;
return p; }

然后您将决定(这是您要遵循的约定)内部的每个字符串都是使用 strdup 堆分配的 - 因此您没有两个别名指针里面。这是设置字符串的函数(如果需要,释放前一个字符串)

void 
set_string_array(struct my_string_array_st*p, unsigned ix, const char*str) {
if (!p || ix>=p->len) return;
free(p->arr[ix]);
char* s = NULL;
if (str) {
s = strdup(str);
if (!s) { perror("strdup"); exit(EXIT_FAILURE); };
};
p->arr[ix] = s;
}

(回想一下,您可以 free(3) 一个 NULL 指针;这是一个空操作)这是一个析构函数,释放所有内部字符串。

void destroy_string_array(struct my_string_array_st*p) {
if (!p) return;
unsigned l = p->len;
for (unsigned ix=0; ix<l; ix++) free(p->arr[ix]);
free (p);
}

当然,这里有一个访问函数:

const char* nth_string_array(struct my_string_array_st*p, unsigned ix)
{
if (!p || ix>=p->len) return NULL;
return p->arr[ix];
}

关于c - 如何定义字符串数组的结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29046478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com