繁体   English   中英

如何为 C 中的字符串数组赋值?

[英]How do I assign a value to an array of strings in C?

所以我使用malloc()创建了一个指针数组。 我最终想要一个字符串数组。 我将如何将字符串值分配给这些 malloced 指针之一?

例如,如果我做了以下事情:

char ** elements= malloc(N* sizeof(char*));

并循环前一个数组以分配单个指针,如下所示:

elements[i] = malloc((50) * sizeof(char));

我们可以使用strncpy()和类似的函数将某些内容复制到字符串中,例如memcpy()或使用我们自己的函数。

我建议使用strncpy()因为它可以防止溢出,因为它会复制指定的长度。

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

typedef unsigned char BYTE;

enum {
    NumStrings = 50,
    MaxStrLen = 50
};

int main(void) {
    char **StrList = malloc(NumStrings * sizeof(char *));
    if (StrList == NULL) {
        perror("malloc");
        exit(1);
    }
    for (BYTE i = 0; i < NumStrings; i++) {
        StrList[i] = malloc(MaxStrLen);
        if (StrList[i] == NULL) {
            perror("malloc");
            exit(1);
        }
        // Here we copy something into the string for example
        strncpy(StrList[i], "test", 50);
        StrList[i][49] = '\0';
        // Print string here to show it's copied
        printf("%s ", StrList[i]);
    }
    putchar('\n');

    for (BYTE i = 0; i < NumStrings; i++) 
        free(StrList[i]);
    free(StrList);
    exit(0);
}

使用当前的标准 C,您将执行以下操作:

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

size_t size = strlen(some_string) + 1; // +1 for null term
elements[i] = malloc(size);
memcpy(elements[i], some_string, size);

...

free(elements[i]);

随着即将推出的“C2x”标准(仍处于草案阶段), strdup可能会被添加到该语言中。 尽管它已经作为 POSIX 支持的非标准扩展广泛使用。 例子:

#include <string.h>

elements[i] = strdup(some_strings[i]);

...

free(elements[i]);

使用#include <string.h>包含字符串函数。 比使用strncpy函数为 char 数组赋值。 要将字符串复制到elements[i] ,请使用以下命令:

strncpy(elements[i], "Hello, world!", 49)

您可以将另一个char数组指针作为第二个参数。 请注意,为了避免删除字符串末尾的空字节,请从实际字符串数组长度中减去1以保留'\\0'最后一个字节。 此外,最好使用calloc(50, sizeof(char))来分配字符串,因为calloc额外用空字节填充它们。 或者,至少,在迭代时添加这一行(将最后一个字节设置为零以使字符串以空字符结尾):

elements[i][49] = '\0';

暂无
暂无

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

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