Im trying to code a chat in C with a graphical interface. On one side, I have a client for my chat, on the other side I have a GTK app to display my chat. To run them both at the same time, I'll be using pthread (open to other suggestions tho).
My problem is that I need both argc and argv in order for my client to work properly. From what I saw, pthread_create() takes as argument a function to execute and only one argument. I saw from other topics that I could use a data structure to contain them both, but I can't seem to cast them properly. Here is what I have :
typedef struct {
int *argc;
char ** argv;
} args_list;
void * simple_client(void * arg){
int argc = (int) arg->argc;
char * argv[] = (char *) arg->argv;
printf("in thread : %d / %s, %s \n", argc, argv[0], argv[1]);
return 0;
}
int main(int argc, char * argv[])
{
printf("int main : %d / %s, %s \n", argc, argv[0], argv[1]);
args_list * args = malloc(sizeof *args);
args-> argc = &argc;
args-> argv = &argv;
pthread_t thread1;
if (pthread_create(&thread1, NULL, simple_client, args)) {
perror("pthread_create");
return EXIT_FAILURE;
}
if (pthread_join(thread1, NULL)) {
perror("pthread_join");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
From this, I get : error: request for member 'argc' in something not a structure or union from int argc = (int) arg->argc; and the same with argv from char * argv[] = (char *) arg->argv;
What would be causing these errors ? And do you think this is a good way of implementating an online chat with a GTK gui ?
Thanks in advance
Define the struct
as so:
typedef struct tARGS
{
int argc;
char **argv;
} ARGS;
Then, in main
:
ARGS args;
args.argc = argc;
args.argv = argv;
Technically, argc
isn't really needed since the following code will process every argument in args
( argv[argc]
is a guaranteed null pointer by the C standard):
ARGS args = *(ARGS *)arg;
while(*args.argv)
{
puts(*args.argv);
args.argv++;
}
A few issues with types here.
simple_client
takes a void*
. In order to use the passed in value as an arg_list
, you need to cast it to one.
void * simple_client(void * argp){
arg_list* arg = (arg_list*) argp;
You don't need an extra level of indirection in arg_list
. It should contain the same types as the arguments of main.
//in main:
args->argc = argc;
args->argv = argv;
//in simple_client:
int argc = arg->argc;
char** argv = arg->argv;
In your original code you were storing the "address of a pointer to a char*" in a "pointer to a char *".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.