c - 在 C 中分配结构的字符串字段

标签 c pointers struct malloc c-strings

我尝试使用这种包含字符串的结构编写一个程序:

typedef struct s_conf
{
    char *shell1;
    char *shell2;
    char *shell3;
    char *shell4;
    char *server_ip;    
} t_conf;

每行解析一个配置文本文件,我得到这些信息并将其存储到变量中,例如 line1 和 line4。现在我想为我的结构字段分配变量 line1 和 line4 的值:

char *line1 = "/var/www/host/current/app/console robot:file";
char *line4 = "192.168.00.00";

t_conf *conf;
if ((conf = malloc(sizeof(t_conf))) == NULL)
        {
            fprintf(stderr, "Malloc error\n");
            return (-1);
        }

strcpy(conf->shell1, line1);
strcpy(conf->server_ip, line4);

printf("line1 : '%s'\n"; line1);
printf("line4 : '%s'\n"; line4);

printf("t_conf->shell1 : '%s'\n", conf->shell1);
printf("t_conf->server_ip : '%s'\n", conf->server_ip);

输出:

line1 : '/var/www/host/current/app/console robot:file'
line4 : '192.168.00.00'
t_conf->shell1 : '/var/www/host/current/app'
t_conf->server_ip : '192.168.00.00'

如何正确分配 c 字符串 t_conf->shell1 ? 我尝试其他函数,如 memcpy()、strdup() 并使用 malloc 分配变量:t_conf->shell1 = malloc(strlen(line1) + 1) 但它给了我相同的结果,我输了line1 的一部分?

最佳答案

I try to write a program using this structure containing strings :

struct s_conf 下面包含 5 个指针。它不包含任何字符串。对于 C 标准库,字符串 是字符的数组,直到并包括最后一个空字符 ('\0')。为了让您的代码正常工作,需要在某个地方为这些数组提供内存。

typedef struct s_conf {
    char *shell1;
    char *shell2;
    char *shell3;
    char *shell4;
    char *server_ip;    
} t_conf;

strcpy(conf->shell1, line1); 失败,因为 conf->shell1 还没有指向副本可用内存的值。


用指向包含所需数据的内存的值填充这 5 个指针。

// allocate memory for the structure
conf = malloc(sizeof *conf);
assert(conf);

// Simply copy the pointer if `line1` will exist for as long as `conf`.
conf->shell1 = line1;

// or
// Create an allocated copy.
conf->shell1 = strdup(line1);
// With this method, be sure to free the memory before freeing conf
...
free(conf->shell1);
free(conf);

strdup() 不是标准库函数,但很常见。如果需要,做一个等价物。示例:(根据您的需要量身定制)

char *my_strdup(const char *s) {
  if (s) {
    size_t sz = strlen(s) + 1;
    char *dest = malloc(sz);
    if (dest) {
      return memcpy(dest, src, sz);
    }
  }
  return NULL;
}

关于c - 在 C 中分配结构的字符串字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40426009/

相关文章:

c - 结构数组的动态分配

C: 多个文件的struct list & fscanf

我可以使用 pcap 库来接收 ipv6 数据包吗?

c - 在 C 中的位图图像中查找水平线

void* 指针的 C++ 替代品(不是模板)

c++ - 使用堆在堆栈中设置值

c++ - 一个简单的多维数组取消引用会很慢吗?

c++ - 如何使结构类型定义在 union C++ 之外可见

c - 修改windows中socket缓冲区大小的默认值

go - 在结构中表示可选 time.Time 的惯用方式