Reputation: 3477
I have been testing some programs in C and I came to review the part of unions, so I made the following program:
#include <stdio.h>
#include <stdlib.h>
void func(union u[])
{
printf("%d\n",u[0]);
printf("%lf\n",u[1]);
printf("%s\n",u[2]);
}
int main(int argc, char *argv[]) {
int i;
i=0;
typedef union{
int i;
double d;
char s[5];
}ArrayN;
ArrayN New_array[3];
New_array[0].i=10;
New_array[1].d=5.5;
New_array[2].s="Hello";
func(New_array);
return 0;
}
I wanted to create a union so that it can store different types of variables. The problem that I got is when I try to run the program, the error I got is:
[Error] parameter name omitted
and points to the function.
I would not like to use pointers, what am I missing?
Thanks
Upvotes: 0
Views: 78
Reputation: 12344
start with making your union declaration visible to both, main and the function. Declare the function parameter correctly. Then use it correctly in the function. you have a few more errors there:
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // need for strcpy
typedef union{
int i;
double d;
char s[6]; // needs to be at least one character longer than the string it contains
}ArrayN;
void func(ArrayN u[])
{
printf("%d\n",u[0].i); // you forgot to use 'i', 'd', 's' fields here
printf("%lf\n",u[1].d);
printf("%s\n",u[2].s);
}
int main(int argc, char *argv[]) {
int i;
i=0;
ArrayN New_array[3];
New_array[0].i=10;
New_array[1].d=5.5;
strcpy(New_array[2].s, "Hello"); // you use an array here, not a char pointer, so, copy all 5 chars into the 6 char array.
func(New_array);
return 0;
}
Upvotes: 2
Reputation: 119877
func
. The word union
is always followed by a tag name or (when defining one) by an open brace. Your union doesn't have a tag name, so you must use a typedef name instead. That is, your parameter needs to look like this:
void func(ArrayN u[])
You cannot pass the union to printf
, you need to pass its separate individual members:
printf("%d\n",u[0].i);
Upvotes: 0
Reputation: 6103
You are missing the type you defined:
Define the union at the beginning of the file:
typedef union{
int i;
double d;
char s[5];
}ArrayN;
Change:
void func(union u[])
to
void func(ArrayN u[])
Upvotes: 0