私は、サーバー側のデーモンをcで作成しようとしており、クライアントからの接続を受け入れます。私は開いている各接続の情報を保持する構造体が必要なので、私は定義された構造体の配列を作成し、動的にreallocでサイズを変更します。構造体の配列を動的に展開する
問題は、配列内に構造体を作成していることです。このエラーが発生し続ける:
test.c:41: error: conversion to non-scalar type requested
私は間違っていますか?
私はほとんどの時間をPHPで費やしていますが、cとnoobです。私は、シンプルで初心者のミスをしていることに気付いています(言い換えれば、私を楽しませてください)。私が何か愚かなことをしているなら、私に知らせてください。私はGoogleで質の高い時間を置いたが、それを理解していない。私は以下のように、より小さな規模で問題を再現しています
をここに私の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;
}
トリックをした! (ほぼ): 次の数行を に変更しました。 ' \t test * x =&test_list [id]; \t x-> id = id; \t x-> ip = malloc(strlen(ip)); \t \t strcpy(x-> ip、ip); \t x-> user = 0; \t x-> str = NULL; ' そして私が手: ' *** glibcの検出*** ./test:のrealloc():無効次のサイズ:私のいずれの場合でループ のために数回の反復の後に... ' 、私が与えましたあなたはポイント(私の最初の質問に答えた)。 – cegfault
nevermind;私はそれを働かせた。助けてくれてありがとう – cegfault