带有指针声明的C动态结构赋值

时间:2013-05-31 11:44:47

标签: c struct typedef

程序在作业附近崩溃。我怎么能让它起作用?提前致谢。对不起,如果是重新发布。在任何地方找不到类似的例子。

#include <stdio.h>

typedef struct _kv
{
    char *key;
    char *value;
} _kv;

typedef struct _kvs
{
    _kv *kv;
    int size;
} _kvs;

main()
{
    _kvs a;

    a.kv[0].key     = "This is key One";
    a.kv[0].value   = "This is value One";

    a.size = 1;

    printf("%s = %s\n", a.kv[0].key, a.kv[0].value);
}

2 个答案:

答案 0 :(得分:1)

你已经创建了指针,但没有为内存腾出空间。您需要通过使用malloc来将一些内存与指针相关联。

a.size = 1;
a.kv = malloc ( a.size * sizeof ( _kv ) );
int i;
const int string_sz = 80;   // Or whatever else the string size should be
for ( i = 0; i < a.size; i++ )
{
    a.kv[i].key = malloc ( string_sz );
    a.kv[i].value = malloc ( string_sz );
}

strcpy ( a.kv[i].key, "This is key one" );
strcpy ( a.kv[i].value, "This is value one" );

答案 1 :(得分:0)

未初始化的指针无法取消引用,您必须首先确保它们指向有效的内存。

_kvs a;

a.kv = malloc(1 * sizeof *a.kv);  /* Allocate a single _kv. */
a.kv[0].key = "key";
a.kv[0].value = "value";
a.size = 1;

或者您可以在堆栈中使用内存:

_kv my_kvs[1];
_kvs a;

a.kv = my_kvs;
a.kv[0].key = "key";
a.kv[0].value = "value";
a.size = 1;