Pregunta

Well I have a library for simulate a dynamic array in c. So I have different functions that create a list and adds nodes to it. In the main function it is supposed that the people that it is using the library will not have an idea of what list is.

main()
{
  list dinarr = new_list(3,'d'); 

In this case, it will create a a list of three nodes. Inside the struct list I just have a data type char data[60]. However, the user well think that it is an array type of double.

  double x = 2.5;
  dinarr = put_list(dinnar,1,&x); 

Here I have a function that, given a position, will put a value in that node. The array was declared as double so it is logical that the user enters a double array. However since I don't know what type of array will be the other that the user created, I have in that function a void pointer, that given the type of the array (double in this case) convert the void pointer to a double pointer and that to a char, so I can put that data in the list. Here I don't have any problems.

  double y = 0;
  y = get_list(dinnar,1); 

Here is the thing I have a double var call y, because I create a double array, then in get_list I send the position and the list, so the function will bring me the data that the user need. In that function I have a switch that in case of the datatype of the array is d (double), c(char), s(string),i(int) or f(float). It converts the char data of the struct list for the kind of type that the array is in this case double. But I do not know how return different types of data with just one argument. I used a struct but then I have to declare that struct in the main, and the main purpose of this, is that the user doesn't notice.

}

So what kind of type, should I declare my function? I used void pointer and struct, but it does not work for me because the user shouldn't know what it is happening inside my library.

¿Fue útil?

Solución

You cannot implement that, C doesn't support overloading or having multiple functions with the same name but different return types.

You can solve it by making the list getter take a pointer to where the caller wants the result:

double y;
get_list(dinnar, &y);

Under the hood your list module copies the value since it knows (from the 'd' format specifier) the size to expect. You can of course generalize that part to just take a size_t itemSize instead of a format letter, to make the list capable of handling any-size items.

It's not as convenient to use though but it's hard to improve on.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top