Variable doesn't change - and changes (separate source files)

I'm having a very weird problem here. I think the resolution is simple, but I just can't figure it out. I'm developing onto GTK+, but that shouldn't affect the problem.

OK, so I have two separate .c files (main.c and convert.c) in my project and one .h (main.h) file. The main.h file looks like this:

1
2
3
4
5
6
7
8
9
#ifndef  MAIN_H
#define  MAIN_H

#include <gtk/gtk.h>

/* The prototype of the convert function (in convert.c) */
void convert(char *name);

#endif 


And the main.c file looks like this:

1
2
3
4
5
6
7
#include "main.h"

int main(int argc, char *argv[])
{
 convert("H");
 return 0;
}


And the convert.c file looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include "main.h"

/* Our conversion function */
void convert(char *name)
{
    /* Check if 'name' contains anything */
	g_print ("%s was pressed\n", (char *) name);
	/* This converts the name of the substance into
	   a new one. */
	if (name == "H") name = "Hydrogen";
	
	/* Check if 'name' has changed */
	g_print ("%s was pressed\n", (char *) name);
}


OK, now onto the problem: When I call the convert(char *name) function from the main function which is in main.c, the variable 'name' doesn't change its contents at all!
What makes the problem weird is when I put the convert(char *name) function into main.c and don't use convert.c in the compiling, the 'name' variable is able to change into "Hydrogen".

So, when convert(char *name) function is in its separate file, convert.h, the command line prints:

H was pressed
H was pressed


And when it's in main.c (above the main(int argc, char *argv[]) function), it prints:

H was pressed
Hydrogen was pressed


I compile the source files with Linux's GCC:

gcc -o program main.c convert.c `gtk-config --cflags` `gtk-config --libs`

I believe this is just an ordinary C thingy.
Last edited on
== can't be used to compare C strings. That's why we have strcmp(). == only compares (in this case) two pointers.
When convert() is in the same file as main(), the array "H" is in the same location, but when it's in a file of it's own, there are two copies of the static array, each in a location of its own. So saying "H" in main.c will translate to, say, 0x48f57c6b, but in convert.c, it will translate to 0x0f3b58ac. And, obviously, 0x48f57c6b!=0x0f3b58ac.

Never compare C strings using ==. Use strcmp() instead.
http://www.cplusplus.com/reference/clibrary/cstring/strcmp.html
Last edited on
helios, you saved my day, truly. Thank you very much! Now the conversion works perfectly, thanks to strcmp().
Topic archived. No new replies allowed.