0
#include <stdio.h>


struct mychar{
    char value;
    struct mychar *nextPtr;
};

typedef struct mychar Mychar;
typedef Mychar *MycharPtr;


void insert(MycharPtr *, char );
void printlist(MycharPtr);


int main(){
    MycharPtr startPtr = NULL;

    char b = 'b';

    insert(&startPtr, b);

    printlist(startPtr);
}

void insert(MycharPtr *sPtr, char newvalue){

    MycharPtr newlinkPtr;

    if (*sPtr == NULL){
        newlinkPtr->value = newvalue;
        newlinkPtr->nextPtr = NULL;
    }

    *sPtr = newlinkPtr;
}


void printlist(MycharPtr currentPtr){
    printf("%c", currentPtr->value);
}

I'm just starting by only adding one char. If I can't even do that, I can't go on doing else.

It gives me segmentation fault, but I don't really know why.

Also, I still don't get the reason why in insert call I should write & but in printlist call I shouldn't write &.

1 Answer 1

1

You haven't actually allocated memory for newlinkPtr. So you're just dereferencing and attempting to write to an uninitialized pointer, resulting in undefined behaviour.

In insert, you can modify it to:

MycharPtr newlinkPtr = malloc(sizeof *newlinkPtr);
if (!newlinkPtr) {
    perror("malloc");
    return;
}

...

This also, sort of, illustrates why typedef'ing a struct pointer could mislead and considered a bad practice. I'd suggest avoiding it.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks a lot. I hate this typedef of ptr too... it was in my book so I thought that for good practice of programming I'd better use it, but it actually confuses me. One question: I don't really get why initializing with malloc is needed... Shouldn't creating a new pointer without malloc actually allocates memory? Why it doesn't and I need malloc?
To be clear, typedef'ing pointer is not always bad (opaque types are created that way). But in this case, it's unnecessary and misleading. re. need for malloc: the definition of mylinkPtr just creates a pointer (for the pointer itself memory is allocated). But it doesn't point to anywhere valid. So you need to make it point to a valid block of memory in order to write.
So when I do MycharPtr newlinkPtr = malloc(sizeof *newlinkPtr); I am actually creating a new struct node and a pointer that points to that struct, right? So this is the reason why before it didn't work, because I was only creating a pointer with MycharPtr newlinkPtr; but not creating the new struct.
That's correct. Without the typedef, it'd look like: struct mychar *newlinkPtr = malloc(sizeof *newlinkPtr);. Does it make it easier to understand?
Yes, thanks you! Wouldn't be the same if I do: Mychar *newlinkPtr = malloc(sizeof(Mychar)); ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.