C和C++结构体初始化的不同

发布时间:2024年01月22日

先看程序:

test.h

#pragma once


#include"stdint.h"


#define RWAVE_PEAK_HISTORY_COUNT  (40)

typedef struct
{
    uint32_t tail;
    uint32_t head;
    uint32_t size;
    uint32_t count;
    int32_t* data;
} circularBuffer32, * p_circularBuffer32;


extern int32_t rWavePeakHistoryData_nv[RWAVE_PEAK_HISTORY_COUNT * 2];
extern circularBuffer32  rWavePeakHistory_nv;

test.c

#include"test.h"


int32_t rWavePeakHistoryData_nv[RWAVE_PEAK_HISTORY_COUNT * 2] = { 0 };
//
//
//circularBuffer32  rWavePeakHistory_nv =                                           /* Values are stored as nanoVolts!                                     */
//{
//	0,  //.tail = 0,
//	0,  //.head = 0,
//	RWAVE_PEAK_HISTORY_COUNT,  //.size = RWAVE_PEAK_HISTORY_COUNT,
//	0,  //.count = 0,
//	&rWavePeakHistoryData_nv[0],  //.data = rWavePeakHistoryData_nv,
//};


circularBuffer32  rWavePeakHistory_nv =                                           /* Values are stored as nanoVolts!                                     */
{
	.tail = 0,
	.head = 0,
	.size = RWAVE_PEAK_HISTORY_COUNT,
	.count = 0,
	.data = rWavePeakHistoryData_nv,
};

注意上面注释的语句,C语言,用注释语句和下面未注释语句这两种形式初始化结构体rWavePeakHistory_nv都是可以的。

但是,C++中则不行,只能用注释语句这种形式初始化结构体!

main.c

#include<stdio.h>

#include"test.h"


int main()
{
	rWavePeakHistoryData_nv[1] = 1;
	printf("rWavePeakHistory_nv.count=%d\n", rWavePeakHistory_nv.count);
	rWavePeakHistory_nv.data++;
	printf("rWavePeakHistory_nv.data[1]=%d\n", *(rWavePeakHistory_nv.data));

	return 0;
}

结果:

将test.c改成test.cpp:

编辑器及编译报错:

一个小笑话,顺便记下报错:

另外,刚开始写错声明数组变量:

extern int32_t rWavePeakHistoryData_nv[RWAVE_PEAK_HISTORY_COUNT * 2];

写成:

extern int32_t rWavePeakHistoryData_nv;

则报间接寻址级别不同的错误:

错误指向这个变量的定义:

即test.c的第4行:

int32_t rWavePeakHistoryData_nv[RWAVE_PEAK_HISTORY_COUNT * 2] = { 0 };

实际是声明处的错。

这种间接寻址级别不同的错误,其实一般就是指针类型不匹配。

文章来源:https://blog.csdn.net/weixin_40194697/article/details/135755522
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。