I get this gcc warning with -Wwrite-strings flag. I want to return a string of chars correctly but I also do not want to use malloc. I've read other posts but can somebody explain how to acheive this in layman wording?

a.c:14: warning: passing argument 1 of ‘VAR1’ discards qualifiers from pointer target type

#include <stdio.h>
#include <string.h>

char *VAR1(char *VAR2)
{
	static char VAR3[12] = "Hello ";
	strcat(VAR3, VAR2);

	return VAR3;
}

int main(void)
{
	printf("%s", VAR1("World!")); // Hello World!

	return 0;
}

Try this

#include <stdio.h>
#include <string.h>

char *VAR1(char *VAR2)
{
	static char VAR3[12] = "Hello ";
	strcat(VAR3, VAR2);

	return VAR3;
}

int main(void)
{
	printf("%s", VAR1((char*)"World!")); // Hello World!

	return 0;
}

Have the code mirror what you're doing:

char *VAR1(const char *VAR2)

Also, make sure you have enough space to write into.

[edit]If he wants the warning...

Try this

why would a solution be to silence the warning with the cast?

Have the code mirror what you're doing:

char *VAR1(const char *VAR2)

Also, make sure you have enough space to write into.

[edit]If he wants the warning...

why would a solution be to silence the warning with the cast?

Depends how you want to look at this....Are you the developer of the app or a developer using the app...i.e. do you have the rights to change the function then yes change it but sometimes(most times) you have to change the data to fit the function...

Why not just turn off the warning? :icon_rolleyes:

Why not just turn off the warning? :icon_rolleyes:

Who's turning off the warning....I'm coercing the data to fit the function. Its done all the time

Who's turning off the warning....I'm coercing the data to fit the function. Its done all the time

Casting is misued a lot of the time. And I would argue that this would be a great example.

If the string itself is nonwritable, the cast silences the warning and passes this nonwritable string to a function that is allowed to write to the string. In this case, the cast might be hiding a bug.

But since the function does not write to the string that is passed, perhaps it would be better to include that in the function signature? That way the compiler doesn't need to play "let's pretend"?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.