0

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

#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);
}
4

2 回答 2

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" );
于 2013-05-31T11:46:40.957 回答
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;
于 2013-05-31T11:49:19.840 回答