【发布时间】:2021-06-10 14:39:07
【问题描述】:
我正在尝试创建一个客户的动态数组,但我没有成功。这是我的代码。当我运行这段代码时,输出是
3
� H
3
4332
3
8939
我认为它正在打印内存的东西,但我不知道为什么。我把我的代码放在这里
int client_counter = 0;
typedef struct client
{
char *pid;
char *message;
}Client;
void store (Client * client_array, char *buf)
{
Client c;
c.pid = strdup (strtok (buf, ":"));
c.message = strdup (strtok (NULL, "\0"));
client_array[client_counter++] = c;
}
int main () {
Client* client_array = malloc (sizeof (struct client));
char buf1[50] = { "1245:message" };
store (client_array, buf1);
char buf2[50] = { "4332:message" };
store (client_array, buf2);
char buf3[50] = { "8939:message" };
store (client_array, buf3);
for (int i = 0; i < client_counter; i++)
{
printf ("%d\n", client_counter);
printf ("%s\n", client_array[i].pid);
}
return 0;
}
我已经尝试过使用这个:
client_array = realloc(client_array, sizeof(struct client) * (client_counter + 1));
在此行之后的存储功能。
client_array[client_counter++] = c;
但它也不起作用。
【问题讨论】:
-
Re "就在这一行之后。",你应该分配内存before你需要它。另外,我怀疑您没有将
realloc返回的指针返回给main。 -
您有
Client * client_array、char *buf和Client* client_array。我不在乎您是否在左侧、右侧或两者都放置空格,但选择一个并坚持下去!