【发布时间】:2011-12-08 01:47:14
【问题描述】:
我目前正在尝试开发一个小规模的程序来模拟一种使用联合作为参数的方法,然后再使用相同的想法开发一个更大规模的程序。联合,由两个结构组成。
在我的程序中,第一个结构有一个 unsigned int,第二个结构有 81 个元素的 char 数组。在下文中,联合具有两种类型的成员结构。接下来是函数ufuncx(); 的原型,它有两个参数,一个联合指针和一个int。
我正在尝试实现一种方法,我可以将它传递给一个函数,一个指向在联合之外定义的两个结构地址之一的联合指针,这两个结构地址也是联合结构成员的一部分。
源代码清单:
/*
this is a program test to see if different types of union members can `enter code as
function arguments of the same union type.
*/
#include <stdio.h>
#include <string.h>
struct id_num
{
unsigned short int idnumber;
};
struct namedisc
{
char name[81];
};
union combo_x
{
struct id_num numtest;
struct namedisc note;
};
int ufuncx(union combo_x *, int);
int main(void)
{
//step 1:
union combo_x *a, *b;
//struct data
struct namedisc text;
struct id_num age;
//step 2a:
//pointer *a - uses the id_num struct
age.idnumber = 25;
a->numtest = age;
//step 2b:
//pointer *b - uses the namedisc struct
strcpy(text.name,"John Doe\0");
b->note = text;
//step 3:
/*=- if you comment this, a pointer error in run time occurs -=*/
printf(".... %s\n",b->note.name);
//step 4:
//show output
ufuncx(a,1);
ufuncx(b,2);
return 0;
}
int ufuncx(union combo_x *data,int part)
{
if(part < 1 || part > 2)
{
printf("we dont have that part...\n");
return -1;
}
if(part == 1)
{
printf(" age = %d ",data->numtest.idnumber);
}
if(part == 2)
{
printf("name = %s ",data->note.name);
}
printf("(it works!)\n");
return 0;
}
这是此源代码的运行时输出:
.... John Doe
age = 25 (it works!)
name = John Doe (it works!)
这看起来不错,而且似乎可以工作,但是有一个问题。
在我的程序的第 3 步中,如果我注释掉 printf(); 语句,我会得到:
age = 25 (it works!)
name = (null) (it works!)
!$h *tl J#@^&
name = (null)(它有效!),在此更改中紧随其后的是随机垃圾,表示错误的指针地址。
注释掉的printf(); 语句不应该在运行时产生影响,但在这种情况下它会产生影响。我的第一个想法是,我有一个指针问题,特别是当我尝试使用间接运算符将 struct text 的地址分配给指针 b 时。
我看不出第 2b 步出了什么问题。我尝试以多种方式对其进行修改,但出现编译器错误。这就是我卡住的地方——因为我遇到了一个逻辑错误。
基于这个程序思想的更大规模的模型,将有两个由许多结构组成的联合作为成员,因为每个结构将有许多不同数据类型的成员(即短整数、字符数组等),这些成员将被传递作为函数的参数。相同的目标,只是扩展了。
提前致谢。
【问题讨论】:
-
容易出错的体现:)
标签: c function pointers struct unions