C语言typedef结构体指针声明引发段错误,求正确实现方法
问题分析与解决
你的段错误核心原因是野指针访问:你声明了WfmInfo_ptr info;但没有让它指向一个有效的WfmInfo结构体实例,此时info是一个随机的垃圾地址,访问info->byte_order必然触发内存错误。另外还有两个小问题:printf格式符不匹配、混用C++语法。
正确实现方式
方式1:栈上分配结构体(简单场景推荐)
直接在栈上创建结构体实例,再用指针指向它:
#include <stdio.h> #include <string.h> #include <stdint.h> #include <inttypes.h> #include <byteswap.h> // 注意头文件名是小写的byteswap.h,不是Byteswap.h #define WFM_HEADER_SIZE 838 typedef struct WfmInfo{ uint16_t byte_order; // char version[8]; uint32_t imp_dim_count; uint32_t exp_dim_count; uint32_t record_type; uint32_t exp_dim_1_type; uint32_t time_base_1; uint32_t fastframe; uint32_t Frames; double tstart; double tscale; double tfrac; double tdatefrac; int32_t tdate; uint32_t dformat; double vscale; double voffset; uint32_t pre_values; uint32_t post_values; uint32_t avilable_values; uint32_t dpre; uint32_t dpost; uint16_t bps; uint32_t code; uint32_t readbytes; uint32_t allbytes ; uint32_t samples; uint64_t curve_offset; uint32_t available_values; } WfmInfo; typedef WfmInfo* WfmInfo_ptr; int testFuck(){ // 栈上创建结构体实例 WfmInfo info_instance; WfmInfo_ptr info = &info_instance; // 初始化结构体成员(可选,避免垃圾值) memset(&info_instance, 0, sizeof(WfmInfo)); info->byte_order = 0x1234; // 示例赋值 // 用正确的格式符打印uint16_t类型 printf("info address %p\n", info); printf("byte order %" PRIu16 "\n", info->byte_order); // PRIu16是inttypes.h提供的标准格式宏 printf("info declared\n"); // 替换C++的cout为printf return 0; }
方式2:堆上动态分配结构体(适合需要长期存活或大结构体)
如果结构体需要在函数返回后继续存在,或者体积较大,用malloc分配内存:
#include <stdio.h> #include <string.h> #include <stdint.h> #include <inttypes.h> #include <byteswap.h> #include <stdlib.h> // 引入malloc/free的头文件 #define WFM_HEADER_SIZE 838 typedef struct WfmInfo{ uint16_t byte_order; // char version[8]; uint32_t imp_dim_count; uint32_t exp_dim_count; uint32_t record_type; uint32_t exp_dim_1_type; uint32_t time_base_1; uint32_t fastframe; uint32_t Frames; double tstart; double tscale; double tfrac; double tdatefrac; int32_t tdate; uint32_t dformat; double vscale; double voffset; uint32_t pre_values; uint32_t post_values; uint32_t avilable_values; uint32_t dpre; uint32_t dpost; uint16_t bps; uint32_t code; uint32_t readbytes; uint32_t allbytes ; uint32_t samples; uint64_t curve_offset; uint32_t available_values; } WfmInfo; typedef WfmInfo* WfmInfo_ptr; int testFuck(){ // 堆上分配内存,记得检查是否分配成功 WfmInfo_ptr info = malloc(sizeof(WfmInfo)); if (info == NULL) { perror("malloc failed"); return 1; } // 初始化成员 memset(info, 0, sizeof(WfmInfo)); info->byte_order = 0x4321; printf("info address %p\n", info); printf("byte order %" PRIu16 "\n", info->byte_order); printf("info declared\n"); // 用完记得释放内存,避免内存泄漏 free(info); return 0; }
额外注意点
- 头文件名:
Byteswap.h要改成小写的byteswap.h,符合系统头文件的命名规范。 - 格式符:打印
uint16_t请用PRIu16(来自inttypes.h),这是跨平台的标准写法;如果用%hu也要确保编译器兼容,但PRIu16更可靠。 - 不要混用C和C++语法:纯C代码里不能用
cout,替换成printf即可。
内容的提问来源于stack exchange,提问作者PatEugene
相关产品推荐
相关产品推荐

