C语言 指针数组的值与指针数组的值相同-奇怪的行为-

  • 本文关键字:数组 指针 语言 arrays c pointers
  • 更新时间 :
  • 英文 :


我这里有一个奇怪的情况。我将描述范围和上下文。

文件交流

/*structs declared as extern in header file */
(struct) strXP A_01 = {values...};
(struct) strXP A_02 = {values...};
(struct) strXP A_03 = {values...};
(struct) strXP A_04 = {values...};

公元前文件

/*structs declared as extern in header file */
(struct) strXP B_01 = {values...};
(struct) strXP B_02 = {values...};
(struct) strXP B_03 = {values...};
(struct) strXP B_04 = {values...};

文件运费到付

strXP * arr_01[4] = {&A_01, &A_02, &B_01, &B_02};
strXP * arr_02[4] = {&A_03, &A_04, &B_03, &B_04};
void receive_array(strXP arr_received[], int size)
{
for(int io = 0; io < size; io++)
{
strXP * const current = &arr_received[io];
etc...
}
}
Main_Loop:

receive_array(*arr_01, 4);

然而,在函数receive_array的调试模式中,"current"接收以下值:

step 01: current equals the values of A_01
step 02: current equals the values of A_02
step 03: current equals the values of A_03 (Expected was B_01)
step 04: current equals the values of A_04 (Expected was B_02)

因此,值在错误的信号中更新,等等。

我不知道我在代码/逻辑中哪里出错了…

您在呼叫receive_array时使用了错误的间接级别

参数类型也错误。

current设置不正确


您的代码非常不完整。但是,我能够推导出一个经过必要修正的等效测试程序。

在相关章节中,我用cpp条件区分了旧代码和新代码:

#if 0
// old code
#else
// new code
#endif

我还添加了[missing]设置和打印代码:

#include <stdio.h>
typedef struct strXP {
int x;
int y;
} strXP;
int value = 1;
#define SETSTR(_sym) 
setstr(&_sym,#_sym)
void
setstr(strXP *ptr,const char *sym)
{
ptr->x = value++;
ptr->y = value++;
ptr->y += 1000;
printf("%s: ptr=%p x=%d y=%dn",sym,ptr,ptr->x,ptr->y);
}
struct strXP A_01;
struct strXP A_02;
struct strXP A_03;
struct strXP A_04;
/*structs declared as extern in header file */
void
setA(void)
{
SETSTR(A_01);
SETSTR(A_02);
SETSTR(A_03);
SETSTR(A_04);
}
struct strXP B_01;
struct strXP B_02;
struct strXP B_03;
struct strXP B_04;
/* structs declared as extern in header file */
void
setB(void)
{
SETSTR(B_01);
SETSTR(B_02);
SETSTR(B_03);
SETSTR(B_04);
}
strXP *arr_01[4] = { &A_01, &A_02, &B_01, &B_02 };
strXP *arr_02[4] = { &A_03, &A_04, &B_03, &B_04 };
#if 0
void
receive_array(strXP arr_received[], int size)
#else
void
receive_array(strXP *arr_received[], int size)
#endif
{
printf("receive_array:n");
for (int io = 0; io < size; io++) {
#if 0
strXP *const current = &arr_received[io];
#else
strXP *const current = arr_received[io];
#endif
printf("  %p %d,%dn", current, current->x, current->y);
}
}
int
main(void)
{
setA();
setB();
#if 0
receive_array(*arr_01, 4);
#else
receive_array(arr_01, 4);
receive_array(arr_02, 4);
#endif
return 0;
}

程序输出:

A_01: ptr=0x4040f0 x=1 y=1002
A_02: ptr=0x4040c8 x=3 y=1004
A_03: ptr=0x4040f8 x=5 y=1006
A_04: ptr=0x4040d0 x=7 y=1008
B_01: ptr=0x4040e8 x=9 y=1010
B_02: ptr=0x4040d8 x=11 y=1012
B_03: ptr=0x404100 x=13 y=1014
B_04: ptr=0x4040e0 x=15 y=1016
receive_array:
0x4040f0 1,1002
0x4040c8 3,1004
0x4040e8 9,1010
0x4040d8 11,1012
receive_array:
0x4040f8 5,1006
0x4040d0 7,1008
0x404100 13,1014
0x4040e0 15,1016

最新更新