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

先看程序:

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

#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:

C和C++结构体初始化的不同_第1张图片

编辑器及编译报错:

C和C++结构体初始化的不同_第2张图片

C和C++结构体初始化的不同_第3张图片

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

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

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 };

实际是声明处的错。

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

你可能感兴趣的:(c语言,c++,开发语言)