'Printing garbage when I convert char* to void* and back in a struct
I'm new to C and am attempting to accept a string from stdin and pass it as a void pointer to a struct (this is a requirement for the program) and then covert it back to a string again in order to print it to stdout.
I tried to print the string from inside a function (the struct was passed as a parameter to the function), but it kept printing out garbage, so I added a print statement in the main method itself to see if it would print garbage there too, and it is.
Here is the struct:
struct Params
{
int key;
void *value;
};
here's part of the main function:
int main(int argc, char *argv[])
{
//blah blah blah
else if (map.f_values == 's')
{
int key; // key will always be an int
printf("Enter a key: ");
fflush(stdin);
scanf("%d", &key);
char* value;
printf("Enter a value: ");
fflush(stdin);
scanf("%s", value);
printf("we got: %s\n", value); //prints correctly
struct Params call2Params = {key, value};
printf("the length of the string is %ld", strlen(call2Params.value));
printf("sending: %d, %s\n", call2Params.key, (char*)call2Params.value); //value prints garbage
}
}
Strange thing is, this works perfectly fine on my mac, but it prints garbage when I run it on a linux VM.
Please let me know if you know what's going on and how to fix it!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
