I am trying to study C, and I am running in to troubles using char* and char arrays. I am using a generic hash-set container from a library (which I don't want to describe in details). This library includes the function
void *HashSetLookup(hashset *h, const void *elemAddr);
which I have to use to search in the hash set to see if the element already exists there (the hash and compare functions are part of the hashset struct). In this case I use the hashset to store pointers to C-strings, or more specifically (char * *) . My problem is that the following code gives a segmentation fault:
char word[1024];
/* Some code that writes to the word buffer */
HashSetLookup(stopList, &word);
while this code works fine (and as expected):
char word[1024];
/* The same code as before that writes to the word buffer */
char* tmp = strdup(word);
HashSetLookup(stopList, &tmp);
free(tmp);
I thought char word[] and char* were basically the same thing. The only difference being that char word[1024] is in the stack with a fixed length of 1024, but tmp in the heap occupying only as much space as necessary (strlen(word)+1).
Therefore I don't understand why I have to make a copy of the string in the heap to be able to call this function. Why does this happen? Is there some more fundamental difference between char* tmp = strdup("something") and char word[1024] = "something"?
char* means a pointer to a character.
char* is a pointer to a character, which can be the beginning of a C-string. char* and char[] are used for C-string and a string object is used for C++ springs. char[] is an array of characters that can be used to store a C-string.
char is 1 byte in C because it is specified so in standards. The most probable logic is. the (binary) representation of a char (in standard character set) can fit into 1 byte.
The type char (*)[20] is read as "pointer to array of size 20 of char . It is not an array of pointers to char . An array (of size 20) of pointers to char would be char *[20] .
You mention you need a char **
and there lies the problem: for an array, word
and &word
mean the same thing - the actual location of the array contents. The reason it works when you use a pointer is because the "pointer" is stored at a different location, while it points to the same array. You don't need an strdup
, you simply need to create a pointer:
char* tmp = word;
HashSetLookup(stopList, &tmp);
Hard to tell without the documentation of HashSetLookup.
But it expects a const void * as its second parameter, so you should pass tmp, and not &tmp, because tmp is already a pointer.
I don't see need for char ** here at all.
Also, you might probably be interested in what HashSetLookup() returns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With