Little
Little

Reputation: 3477

passing an union to a function does not recognize the parameter name

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

Answers (3)

Serge
Serge

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

n. m. could be an AI
n. m. could be an AI

Reputation: 119877

  1. You need to define your union in the file scope before you use it in func.
  2. 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[])
    
  3. You cannot pass the union to printf, you need to pass its separate individual members:

    printf("%d\n",u[0].i);
    

Upvotes: 0

EylM
EylM

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

Related Questions