动态扩展struct数组

时间:2011-10-24 03:25:54

标签: c struct malloc dynamic-arrays

我(尝试)在c中编写服务器端守护程序,它接受来自客户端的连接。我需要一个结构来保存每个打开的连接的信息,所以我创建了一个我定义的结构的数组,并且我使用realloc动态地重新调整大小。

我遇到的问题是在数组中创建结构。我一直收到这个错误:

test.c:41: error: conversion to non-scalar type requested

我做错了什么?

我把大部分时间花在PHP上,而且我是c的菜鸟。我意识到我正在犯一些简单的,初学者的错误(换句话说,随意取笑我)。如果我做了一些愚蠢的事,请告诉我。我已经将我的质量时间用于谷歌,但还没有弄清楚。我已经在较小规模上复制了这个问题,如下所示:

这是我的test.h:

typedef struct test_ test;

这是我的test.c:

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

//define the struct
struct test_ {
    int id;
    char *ip;
    int user;
    char *str;
};

//yes, the list needs to be global
test *test_list;


//
// add an item to the global list
//
int add(int id, char *ip, int size)
{
    //
    // increment size
    if(id>size) {
        size = id;
        //try to expand the list
        test *tmp = realloc(test_list,size);
        if(tmp) {
            //it worked; copy list back
            test_list = tmp;
        } else {
            //out of memory
            printf("could now expand list\n");
            exit(1);
        }
    }
    //
    // HERE IS THE TROUBLE CODE::
    test_list[id] = (struct test)malloc(sizeof(test)+(sizeof(int)*5)+strlen(ip)+1);
    test_list[id].id = id;
    test_list[id].ip = malloc(strlen(ip));
        strcpy(test_list[id].ip,ip);
    test_list[id].user = 0;
    test_list[id].str = NULL;
}

//
// main
//
int main(void)
{
    //initialize
    int size = 1;
    test_list = malloc(size*sizeof(test));
    //add 10 dummy items
    int i;
    for(i=0; i<10; i++) {
        size = add(i, "sample-ip-addr", size);
    }
    //that's it!
    return 0;
}

2 个答案:

答案 0 :(得分:0)

'malloc'的返回值是您分配的内存地址。你不能把它强制转换为结构。这甚至意味着什么?

你想要的东西:test_list = realloc(test_list,num_alloc * sizeof(test _));

答案 1 :(得分:0)

尝试更改

test *tmp = realloc(test_list,size);

test *tmp = realloc(test_list,size*sizeof(test));

然后删除

test_list[id] = (struct test)malloc(sizeof(test)+(sizeof(int)*5)+strlen(ip)+1);

为test_list分配时,已分配的struct的每个成员已经有空间,因此您不需要再次执行此操作。你只需要为struct

中的任何指针分配