Send number / character / string to void* function - c

Is there a way to do something like this : ?
void set(void* data, void *value, t_flags type)
{
if (type & INT)
*(int*)data = *(int*)value;
if (type & UINT)
(...)
}
int i;
set(&i, 42, INT);
My set function works but I don't know how to call it with number, char '', or string "".
Edit : I've forgot the last argument, but the problem come from the 42 argument.

A few things. First, since you're using a void* (which is appropriate) for value, you need to pass a void* as your second argument, instead of a constant. This will work to copy one variable to the next, but there are more efficient ways.
Second, note that for passing a string, you need to pass a pointer to a char pointer, and the char* will get set by the function. (It's up to you whether it's a "soft copy" or "hard copy" - i.e. whether the pointer points to the same place in memory or to another copy of the same string. You said you had set implemented, so I'm guessing you already have it the way you want.
You haven't included your t_flags enum, so I guessed appropriate values.
char c = 'c';
char* str = "str";
int i = 42;
char c2;
char* str2;
char i2;
set(&c2, &c, CHAR); /* presumably you have a CHAR flag? */
set(&str2, &str, CHARPTR); /* presumably you have a CHARPTR flag? */
set(&i2, &i, INT);
The bigger question for me is why you would want to do this, especially since in your flag you already need to know the type. It's much cleaner (and has much better type checking) to simply do:
c2 = c;
str2 = str;
i2 = i;
I'm assuming this is just for learning about functions, or it's massively simplified for a complex issue. Either way, that's how you do it.

Maybe you want this:
void set(void* data, void *value, t_flags type)
{
if (type & INT)
*(int*)data = *(int*)value;
if (type & UINT)
*(unsigned int*)data = *(unsigned int*)value;
if (type & STRING)
strcpy((char*)data, (char*)value);
...
}
int i;
char string[100] ;
set(&i, 42, 1<<INT);
set(string, "Hello world", 1<<STRING) ;
But it's weird anyway.

Related

C - Function processing a const *

I have a function which search something in a const *. And returns such a const * to the found element. Therefore the function is not changing anything and I actually want to maintain the "const" for readability and reuseability.
But I have another function which calls the function with just a * and then works with the returned value. But in this use-case the value should be changed. But because the returned value is a const * I can not do that.
Would should I adjust in my programming pattern to evade that problem?
const void* search_min_vector_element(const void* vector, size_t length, size_t element_size, int(*cmp_fnc) (const void*, const void*));
This is the first function.
void* min_element = search_min_vector_element((unsigned char*) vector + (i * element_size), length - i, element_size, cmp_fnc);
And that is the call in the second one. vector is void* in this case. And because of that I want to modify it.
Thanks for your help.
You can pick which function to execute based on the type of the argument. Write a _Generic macro to select which types to allow, then call the appropriate function based on that. Example:
#include <stdio.h>
char* print_str (char* str)
{
printf("%s\n", str);
return str;
}
const char* print_str_const (const char* str)
{
printf("const %s\n", str);
return str;
}
#define print(str) \
_Generic((str), \
const char*: print_str_const, \
char*: print_str) (str)
int main(void)
{
const char* cstr = "hello";
char* str = "world";
cstr = print(cstr); // ok
str = print(str); // ok
cstr = print(str); // ok
//str = print(cstr); // compiler error, incorrect assignment
//str = print((void*)str); // compiler error, wrong type
}
In C++ you have a lot of options to deal with this. But since this is C, create another function is the best solution I can currently come up with:
const void* search_min_vector_element_const(const void* vector, size_t length, size_t element_size, int(*cmp_fnc) (const void*, const void*));
void* search_min_vector_element ( void* vector, size_t length, size_t element_size, int(*cmp_fnc) ( void*, void*));
You can also force-cast the result directly:
void* min_element = (void*)search_min_vector_element((unsigned char*) vector + (i * element_size), length - i, element_size, cmp_fnc);
I would really recommend to change the return type (if you can) to not be a constant value. It is really not the search_min_vector_element's business what another function shall do with the result.
If you cannot change the return type, then you will need to:
const void* value = search_min_vector_element(....)
void* second_no_const_value = *value; // copy value of the value pointed by constant pointer.
Since you know for a fact that you hold a non-const pointer to vector, you should simply cast the const pointer you receive:
void* min_element = (void*)search_min_vector_element(...);
Technically you may cast from const char* to char* through an explicit cast without yielding undefined behaviour per se; But if you alter a value that must not be altered (e.g. a string literal), you get undefined behaviour then. So the const-qualifier will not prohibit a change of the underlying data, but when used as qualifier in a function argument or return value, the function prototype pretends that the value is not meant to be altered.
Hence, if you - or a library - provides a function with return type const char*, without knowing the implementation, one shall not assume that the returned value points to memory that may be altered. See the following example illustrating this. Functions validImpl1 and validImpl2 have - apart from the name - the same signature but different implementations. Provided that you pass in a parameter which's content may be altered, casting the return value to char* for the first is OK, but for the second one it yields UB. So unless you know the internals of the function, you should never cast from const char* to char *:
const char* validImpl1(const char* t) {
return t;
}
const char* validImpl2(const char* t) {
return "Hello!";
}
int main() {
char x[100] = "Herbert";
char* t=(char*) validImpl1(x);
*t = 'a'; // OK
printf("%s\n",t);
char* t2=(char*) validImpl2(x);
*t2 = 'a'; // Undefined behaviour here.
printf("%s\n",t2);
}
In your case, if you are the one offering the function and knowing about the implementation details, you could offer two functions, one with const char* and one with char*, where the latter simply calls the former. So the ones who use your functions can rely on that what the function prototypes pretend.

assign pointer from argv in function

I am trying to assign a pointer correctly from the programs **argv. When I assign data in the main function it works fine, but when I attempt to place that logic into a separate function it does not.
What am I doing wrong here?
void parse_args(char *argv[ ], unsigned char *data, *data_len, *nprocs){
data = (unsigned char *)argv[1];
*data_len = strlen(argv[1]);
*nprocs = atoi(argv[2]);
}
int main(int argc, char **argv) {
unsigned char *data;
int data_len;
int nprocs;
// this doesnt work (for data)
parse_args(argv, data, &data_len, &nprocs)
// this works (for data)
data = (unsigned char *)argv[1];
}
This line
data = (unsigned char *)argv[1];
modifies a local copy of main's local data, because all parameters, including pointers, are passed by value. If you would like to modify data inside main, pass it by pointer (i.e. you need a pointer to pointer now):
void parse_args(char *argv[ ], unsigned char **data_ptr, int *nprocs) {
...
*(data_ptr) = (unsigned char *)argv[1];
...
}
your function needs to be passed a char * [] (which is equivalent to a char** in an argument specification). You shouldn't specify the type when calling a function, that should have given you a compiler error (char * is not to be used here!)
// this doesnt work (for data)
parse_args(char *argv, data, &data_len)
must be replaced by
parse_args(argv, data, &data_len)
So, next, you pass a pointer data , but you pass that pointer by value, i.e. your parse_args gets a nice copy of that pointer (which, technically, is just an address stored in a variable), and then you modify that copy. You might want to pass it like data_len:
void parse_args(char *argv[ ], unsigned char **data, *data_len, *nprocs){
..
parse_args(argv, &data, &data_len, &nprocs)
All in all, this doesn't seem to be a great attempt at argument parsing. There's lots of libraries out there to do that for you, and if you want to stay old-school, I'd recommend using gengetopt, which generates all the parsing code you need and has nice documentation.

Re-typecasting a variable, possible?

Is it possible to recast the a variable permanently, or have a wrapper function such that the variable would behave like another type?
I would want to achieve something I posted in the other question:
Typecasting variable with another typedef
Update: Added GCC as compiler. May have a extension that would help?
Yes, you can cast a variable from one type to another:
int x = 5;
double y = (double) x; // <== this is what a cast looks like
However, you cannot modify the type of the identifier 'x' in-place, if that is what you are asking. Close to that, though, you can introduce another scope with that identifier redeclared with some new type:
int x = 5;
double y = (double) x;
{
double x = y; // NOTE: this isn't the same as the 'x' identifier above
// ...
}
// NOTE: the symbol 'x' reverts to its previous meaning here.
Another thing you could do, though it is really a horrible, horrible idea is:
int x = 5;
double new_version_of_x = (double) x; // Let's make 'x' mean this
#define x new_version_of_x
// The line above is pure evil, don't actually do it, but yes,
// all lines after this one will think 'x' has type double instead
// of int, because the text 'x' has been rewritten to refer to
// 'new_version_of_x'. This will likely lead to all sorts of havoc
You accomplish that by casting then assigning.
int f(void * p) {
int * i;
i = (int *)p;
//lots of code here with the i pointer, and every line
//really thinks that it is an int pointer and will treat it as such
}
EDIT From the other question you linked:
typedef struct {
unsigned char a;
unsigned char b;
unsigned char c;
} type_a;
typedef struct {
unsigned char e;
unsigned char f[2];
} type_b;
//initialize type a
type_a sample;
sample.a = 1;
sample.b = 2;
sample.c = 3;
Now sample is initialized, but you want to access it differently, you want to pretend that in fact that variable has another type, so you declare a pointer to the type you want to "disguise" sample as:
type_b * not_really_b;
not_really_b = (type_b*)&sample;
See, that is the whole magic.
not_really_b->e is equal 1
not_really_b->f[0] is equal 2
not_really_b->f[1] is equal 3
Does this answer your question?
The other answers are better (declare a variable of the type you want, and do an assignment). If that's not what you're asking for, you could use a macro:
long i;
#define i_as_int ((int)i)
printf( "i = %ld\n", i);
printf( "i = %d\n", i_as_int);
But wouldn't it be clearer to just say (int) i if that's what you mean?
As long as you realize in C pointers are nothing but addresses of memory
locations of certain types, you should have your answer. For example the
following program will print the name of the file
int main(int argc, char *argv[]) {
int *i;
i = (int *) argv[0];
printf("%s\n", argv[0]);
printf("%s\n", ((char *) i));
}

idiomatic C for const double-pointers

I am aware that in C you can't implicitly convert, for instance, char** to const char** (c.f. C-Faq, SO question 1, SO Question 2).
On the other hand, if I see a function declared like so:
void foo(char** ppData);
I must assume the function may change the data passed in.
Therefore, if I am writing a function that will not change the data, it is better, in my opinion, to declare:
void foo(const char** ppData);
or even:
void foo(const char * const * ppData);
But that puts the users of the function in an awkward position.
They might have:
int main(int argc, char** argv)
{
foo(argv); // Oh no, compiler error (or warning)
...
}
And in order to cleanly call my function, they would need to insert a cast.
I come from a mostly C++ background, where this is less of an issue due to C++'s more in-depth const rules.
What is the idiomatic solution in C?
Declare foo as taking a char**, and just document the fact that it won't change its inputs? That seems a bit gross, esp. since it punishes users who might have a const char** that they want to pass it (now they have to cast away const-ness)
Force users to cast their input, adding const-ness.
Something else?
Although you already have accepted an answer, I'd like to go for 3) namely macros. You can write these in a way that the user of your function will just write a call foo(x); where x can be const-qualified or not. The idea would to have one macro CASTIT that does the cast and checks if the argument is of a valid type, and another that is the user interface:
void totoFunc(char const*const* x);
#define CASTIT(T, X) ( \
(void)sizeof((T const*){ (X)[0] }), \
(T const*const*)(X) \
)
#define toto(X) totoFunc(CASTIT(char, X))
int main(void) {
char * * a0 = 0;
char const* * b0 = 0;
char *const* c0 = 0;
char const*const* d0 = 0;
int * * a1 = 0;
int const* * b1 = 0;
int *const* c1 = 0;
int const*const* d1 = 0;
toto(a0);
toto(b0);
toto(c0);
toto(d0);
toto(a1); // warning: initialization from incompatible pointer type
toto(b1); // warning: initialization from incompatible pointer type
toto(c1); // warning: initialization from incompatible pointer type
toto(d1); // warning: initialization from incompatible pointer type
}
The CASTIT macro looks a bit complicated, but all it does is to first check if X[0] is assignment compatible with char const*. It uses a compound literal for that. This then is hidden inside a sizeof to ensure that actually the compound literal is never created and also that X is not evaluated by that test.
Then follows a plain cast, but which by itself would be too dangerous.
As you can see by the examples in the main this exactly detects the erroneous cases.
A lot of that stuff is possible with macros. I recently cooked up a complicated example with const-qualified arrays.
2 is better than 1. 1 is pretty common though, since huge volumes of C code don't use const at all. So if you're writing new code for a new system, use 2. If you're writing maintenance code for an existing system where const is a rarity, use 1.
Go with option 2. Option 1 has the disadvantage that you mentioned and is less type-safe.
If I saw a function that takes a char ** argument and I've got a char *const * or similar, I'd make a copy and pass that, just in case.
Modern (C11+) way using _Generic to preserve type-safety and function pointers:
// joins an array of words into a new string;
// mutates neither *words nor **words
char *join_words (const char *const words[])
{
// ...
}
#define join_words(words) join_words(_Generic((words),\
char ** : (const char *const *)(words),\
char *const * : (const char *const *)(words),\
default : (words)\
))
// usage :
int main (void)
{
const char *const words_1[] = {"foo", "bar", NULL};
char *const words_2[] = {"foo", "bar", NULL};
const char *words_3[] = {"foo", "bar", NULL};
char *words_4[] = {"foo", "bar", NULL};
// none of the calls generate warnings:
join_words(words_1);
join_words(words_2);
join_words(words_3);
join_words(words_4);
// type-checking is preserved:
const int *const numbers[] = { (int[]){1, 2}, (int[]){3, 4}, NULL };
join_words(numbers);
// warning: incompatible pointer types passing
// 'const int *const [2]' to parameter of type 'const char *const *'
// since the macro is defined after the function's declaration and has the same name,
// we can also get a pointer to the function
char *(*funcptr) (const char *const *) = join_words;
}

Change string pointed by pointer

Many functions in c take pointer to constant strings/chars as parameters eg void foo(const char *ptr) . However I wish to change the string pointed by it (ptr).how to do it in c
You can just cast away the const:
void evil_function(const char *ptr)
{
char *modifiable = (char *) ptr;
*modifiable = 'f';
}
Note that this is dangerous, consider cases where the data being passed to the function really can't be changed. For instance, evil_function("bar"); might crash since the string literal is often placed in read-only memory.
Don't do it as it will cause your code to behave unpredictably. Basically the string pointed by const char* may be stored in the read-only section of your program's data and if you try to write something there, bad things will happen. Remember that foo can be called as foo("Test"), here you have not allocated memory for "Test" yourself, you just have a pointer to memory which contains the string. This memory may be read-only.
You can copy it to another piece of memory, and modify it there.
If you cast it to non-const, and then modify, chances are good you'll just segfault.
void foo(const char *x);
char data[4] = "Hi!";
int sum = 0;
for (int k=0; k<strlen(data); k++) {
foo(data); /* foo first */
sum += data[k];
}
printf("%d\n", sum);
Because foo() does not change its argument, the compiler can change this code to
void foo(const char *x);
char data[4] = "Hi!";
int sum = 0;
for (int k=0; k<strlen(data); k++) {
sum += data[k]; /* sum first */
foo(data);
}
printf("%d\n", sum);
But, if foo() changes the values in the data array, the results will be different according to the order the compiler chose to code the loop!
In short: don't lie to your compiler
How to lie to the compiler
Cast the const away
void foo(const char *readonly) {
char *writable = (char *)readonly;
/* now lie to the compiler all you like */
}
by notation "const char *ptr" we are telling Compiler
that ptr contains should not be changed.
Just, we can't change it!
The whole reason the const is so to express that the underlying content is not to be modified by this function, so don't change it because that will most likely break some code which is relying on the constness. other then that you can always cast the constness away using either const_cast<char*> or by directly casting the pointer
If you do it like this:
void dont_do_this_at_home(const char *ptr)
{
char **steve-o_ptr = (char **) &ptr;
char *bam_margera = "viva la bam";
*steve-o_ptr = bam_margera;
}
Then the pointer that you send into the function will be changed despite being a const pointer, the other suggestions so far only let you change the contents of the string, not the pointer to the string.
And I agree with the others that you shouldn't, ever, "un-const" any parameter you get, since the callee may really depend on that there are no side-effects to the function regarding those parameters.
There is also this way to get rid of the warnings/errors
typedef struct {
union {
const void* the_const;
void* the_no_const;
} unconsting;
}unconst_t;
/* Here be dragons */
void* unconst_pointer(const void* ptr) {
unconst_t unconst.unconsting.the_const = ptr;
return unconst.unconsting.the_no_const;
}
As you see it is quite possible and popular to actually do this, but you have to know what you are doing or mysterious faults may appear.

Resources