找回密码
 注册
查看: 1430|回复: 4

关于C语言结构体双重成员指针的内存分配和使用

[复制链接]
发表于 2006-8-1 09:15:41 | 显示全部楼层 |阅读模式
test.h:
#ifndef _TEST_H_
#define _TEST_H_

typedef struct _yx_value
{
        int len;
        char *value;
}yx_value;

#endif



test.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "test.h"
main()
{
        yx_value **test;
        test = NULL;
        test = (yx_value **)malloc(sizeof(yx_value*) * 2000);
        memset(test,0,sizeof(yx_value*) * 2000);
    test[0][0].value = (char*)malloc(1200);
        test[0][0].len = 10;

        //strcpy(test[0][0].value,"aaa");
}



黑体的部分会出现段错误,请高手指点下到底如何使用!!!
发表于 2006-8-2 11:08:23 | 显示全部楼层
test没初始化完全吧?你只初始化了一级。
[code:1]
test = (yx_value**)malloc(sizeof(yx_value*)*2000);
for (int i = 0; i < 2000; ++i)
    test[i] = (yx_value*)malloc(sizeof(yx_value) * N); //N是第一维大小
[/code:1]

附:malloc后要记得free:
[code:1]
for (int i = 0; i < 2000; ++i) {
    free(test[i]);
}
free(test);
[/code:1]
也不要忘了你的test[0][0].value
回复

使用道具 举报

发表于 2006-8-2 11:44:21 | 显示全部楼层
malloc(sizeof(yx_value*) * 2000);
按这个意思,一维就行了,为什么要弄成二维呀?
回复

使用道具 举报

发表于 2006-8-2 12:03:01 | 显示全部楼层
那样malloc出来的是指针,而没有为其分配实际资源,即未初始化。
回复

使用道具 举报

 楼主| 发表于 2006-8-2 16:05:23 | 显示全部楼层
恩,搞出来了,要初始化两次
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

GMT+8, 2025-2-6 22:05 , Processed in 0.025414 second(s), 15 queries .

© 2001-2025 Discuz! Team. Powered by Discuz! X3.5.

快速回复 返回顶部 返回列表