3
votes

I Have a struct, and a constructor method for it. However, I am unable to create initialize the struct properly. In the parameters, I pass a pointer to that struct type, and all its instance variable(sorry for using java terminology, new to C). here is my code for the method.

 typedef struct anagramElement anagramElement;
 struct anagramElement {
    char* word;
    char* key;
 };

void createAnagramElement(char* const word, char* const key, anagramElement* rv)
{
    rv = (anagramElement*) malloc(sizeof(anagramElement));
    rv->word = word;
    rv->key = key;

}

In the main after, passing anagramElement *ptr, char *Word, char*key, when printing the elements data, segmentation fault occurs. NOTE:I Cannot change the parameters or the method return type.

3

3 Answers

6
votes

You are passing rv by value. Anything you do to it won't "stick" beyond the function call. To avoid double pointers, refactor so createAnagramElement() returns the pointer.

anagramElement* createAnagramElement(char* const word, char* const key)
{
    // don't cast the result of malloc()
    anagramElement* rv = malloc(sizeof(anagramElement));
    if (rv != NULL) {
        // Just storing pointers to strings (not copies) so you need to be
        // sure the strings don't go out of scope...
        rv->word = word;
        rv->key = key;
    }
    return rv;
}

If you can't change the parameters (per comments), perhaps createAnagramElement() is supposed to initialize an already allocated anagramElement:

void createAnagramElement(char* const word, char* const key, anagramElement* rv)
{
    // Don't change value of rv, just change values in the struct.
    // rv = (anagramElement*) malloc(sizeof(anagramElement));
    // Should also NULL check rv, but ignoring for now.
    rv->word = word;
    rv->key = key;
}

You would call it like:

anagramElement    instance;
createAnagramElement("hello", "world", &instance);
0
votes
void createAnagramElement(char* const word, char* const key, anagramElement** prv)
{
    *rv = (anagramElement*) malloc(sizeof(anagramElement));

or

anagramElement* createAnagramElement(char* const word, char* const key)
{
    anagramElement *rv = (anagramElement*) malloc(sizeof(anagramElement));
    ...
    return rv;
}
0
votes

Error handling is also important issue. While using double pointer, you can use a return value for result status like failed or success:

int createAnagramElement(char* const word, char* const key, anagramElement** element)
{
     *element= (anagramElement*) malloc(sizeof(anagramElement));

     if(*element == NULL){ return ANAGRAM_ELEMENT_FAILED; }

     //some operations

     return ANAGRAM_ELEMENT_SUCCESS;

}