首页 > 解决方案 > C在存储在数组中的结构中打印char数组

问题描述

我在尝试打印和存储 char 数组时遇到了麻烦。char 数组“id”存储在结构中,然后存储在该结构的数组中。当我尝试打印 id 时出现段错误。任何帮助都会很棒。这是结构

{
  const int NUM_MAX_FILES = 50;
  const int FILE_NAME_MAX_LENGTH = 256;
  typedef struct {
    char id[10]; //id
    char* addr; // The IP of the peer
    int file_count; // number of files
    char files[NUM_MAX_FILES][FILE_NAME_MAX_LENGTH]; // The files the peer broadcasts
} peer_struct;

然后将其存储到数组中

peer_struct more_peers[50];

我有一个嵌套循环,它比较每个对等点及其文件,以搜索匹配的文件。效果很好,但是当我尝试通过匹配获取对等方的 id 时,我遇到了段错误。这是匹配的代码。

if(strcmp(buf,more_peers[i].files[y]) == 0){
    printf("Found a match: ");
    printf("%s\n",more_peers[i].id); <-- this is where I get a seg fault.
    strcpy(val,more_peers[i].id);//store the value
}

这是添加具有 id 的新对等点的代码

 recv(new_tcp_s, buf, MAXDATASIZE, 0);
 buf[numbytes] = '\0';
 strcpy(tmp_peer.id,buf);
 printf("REG publish: peer id %s\n", tmp_peer.id ); <-- no seg fault here it 
 more_peers[ap_count] = tmp_peer;                   also prints the correct id

标签: arraysc

解决方案


在你写的评论中numbytes是 100。这意味着你正在写超过id数组的末尾,它只有 10 个字节长。

好的做法是用将目标数组的大小作为参数的函数替换 strcpy。例如:

snprintf(tmp_peer.id, 10, "%s", buf);

推荐阅读