arrays - 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
解决方案
在你写的评论中numbytes
是 100。这意味着你正在写超过id
数组的末尾,它只有 10 个字节长。
好的做法是用将目标数组的大小作为参数的函数替换 strcpy。例如:
snprintf(tmp_peer.id, 10, "%s", buf);
推荐阅读
- php - Wordpress:如何以编程方式创建帖子并在之前检查重复项
- cmake - 如果有的话,怎么可能检测到 CMakeLists.txt 是由“emcmake cmake”而不是“cmake”运行的?
- node.js - 来自构建器的 JEST Mock 实现
- reactjs - 为什么 Material UI 的 makestyle 不再影响线性进度条了?
- android-studio - Android Studio 生成数百个重复的“2”文件
- android - 如何跟踪蓝牙低功耗信号中传输的数据包?
- javascript - JavaScript 内部匿名函数无法访问成员?
- php - 在 WP_Options 中保存多维数组
- elixir - 如何在 elixir 中更新嵌套映射中的条目
- android - 如何在 Xamarin.Forms Map 中解决/抑制 DeadObjectException