I have two functions. One that returns the part of the string for me. Don't ask me why I'm doing it inside a function because I want to run this inside a thread.
When I try to get the return value from another function that will return and store it inside a variable an error occur. It says Invalid initializer.
Long time no coding with C programming language. So I'm sorry if there are some basic mistakes.
Can anyone help with this problem?
My code goes like below:
void *encrypt(char data[])
{
//code goes here
return data[];
}
void *firstThread(void *message)
{
code goes here
.
.
.
char message[40] = encrypt(data);//returns Invalid Inıtıalızer
}
CodePudding user response:
The both functions are invalid.
In the first function the return expression is wrong
return data[];
You have to write
return data;
The compiler adjusts the function parameter having the array type to pointer to the array element type like
void *encrypt(char *data);
This pointer is returned from the function casted to the type void *
.
In the second function you are trying to initialize an array with a pointer of the type void *
char message[40] = encrypt(data);//returns Invalid Inıtıalızer
You may not do that. Instead you could write for example
#include <string.h>
//...
void *firstThread(void *message)
{
code goes here
.
.
.
char message[40];
strcpy( message, encrypt(data) );
}
provided that the returned pointer from the function encript
points to a string. Otherwise you need to supply some way also the size of the pointed array to use the function memcpy
instead of strcpy
.
Or you could just declare within the function firstThread
a pointer provided that the pointed array will be still alive
void *firstThread(void *message)
{
code goes here
.
.
.
char *message = encrypt(data);
}
CodePudding user response:
You cannot assign pointers to arrays!
If you want to initialise arrays you need to provide an appropriate initialiser like:
char message[40] = { 1, 2, 3 /* rest will be 0 };
If you want the array to contain data you receive via some pointer you need to explicitly copy it:
char message[40];
memcpy(message, encrypt(data), 0);
Well, in above statement nothing will be copied. Instead of 0
you need to provide the minimum of message
's size and the size of the data returned by your function.
Apart from you have a duplicate variable name: message
as parameter and message
as local variable.