0

I'm trying to do a program that inserts and deletes students from a linked list and when I try to insert a student at the end of the list but it doesn't work. I'm pretty sur that I the function algorithm is right, but still. Anyways, here's the code:

void InsetEnd(){

stud *temp, *newnode;   
char n[15];
int a;

printf("Student: \n");
printf("Name: ");
scanf("%s", n);
printf("Age: ");
scanf("%d", &a);

strcpy(newnode->name, n);
newnode->age=a;

temp=head;

while(temp!=NULL){
    temp=temp->next;
}
temp = (stud *) malloc (sizeof(stud));

newnode->next = NULL;   
temp->next = newnode; }
Yacine
  • 9
  • 1
  • 6
  • 1
    This loop serves little purpose: `while(temp!=NULL){ temp=temp->next; }`. You might as well just replace it with `temp = NULL;` – r3mainer Apr 05 '17 at 21:55
  • [Dont cast return of malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – TheQAGuy Apr 05 '17 at 21:56

4 Answers4

0

For starters the pointer newnode has indeterminate value. Thus these statements

strcpy(newnode->name, n);
newnode->age=a;

result in undefined behavior.

This loop

while(temp!=NULL){
    temp=temp->next;
}

does not make sense because it is evident that after the loop the pointer temp will be equal to NULL.

And you have to change the last pointer in the list after which the new node is inserted.

The function can look at least the following way (though using the function scanf with a character array as it is used in your program is unsafe)

void InsetEnd()
{
    stud *newnode;
    stud **temp;   
    char n[15];
    int a;

    printf("Student: \n");
    printf("Name: ");
    scanf("%s", n);
    printf("Age: ");
    scanf("%d", &a);

    newnode = ( stud * )malloc( sizeof( stud ) );

    strcpy( newnode->name, n );
    newnode->age = a;
    newnode->next = NULL;

    temp = &head;

    while ( *temp != NULL ) temp = &( *temp )->next;

    *temp = newnode;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

I was able to solve the problem. It was just the allocation place in the function. I actually had to allocate memory before creating the node, which if you inverse it will not create anything and it will only display garbage.

void InsetEnd(){

stud *temp, *newnode;   
char n[15];
int a;

printf("Student: \n");
printf("Name: ");
scanf("%s", n);
printf("Age: ");
scanf("%d", &a);

newnode = (stud *) malloc (sizeof(stud));
strcpy(newnode->name, n);
newnode->age=a;

temp=head;

while(temp->next!=NULL){
    temp=temp->next;
}

newnode->next = NULL;
temp->next = newnode;   }
Yacine
  • 9
  • 1
  • 6
0

Seems like you caught your own issue. Allocating memory before trying to access or set data is essential! There are a few more things I felt like I need to mention to help you in the future.

void InsetEnd(stud *head) { // pass head pointer, becomes local pointer so its not overriden
    if (!head) 
        return; // dont do anything if list does not exist

    stud *newnode; // no need for tmp anymore
    char n[15] = ""; // initialize
    int a;

    printf("Student: \n");
    printf("Name: ");
    scanf("%14s", n); // take only 14 chars, leaving the 15th '\0' or you'll have problems reading long names after
    printf("Age: ");
    scanf("%d", &a);

    newnode = calloc(1,sizeof(*newnode)); // use calloc to avoid junk
    // ^ type casting a return of void* is not necessary in c

    strcpy(newnode->name, n);
    newnode->age=a;

    while(head->next) // NULL is pretty much false
        head=head->next;

    // no need to set newnode next to null, its already null from calloc
    head->next = newnode;   
}

Hope this helps!

V. Sim
  • 101
  • 5
-1

I will try to explain it from the following example

  #include <iostream>

    /* run this program using the console pauser or add your own getch, system("pause") or input loop */
    class Node {
    public:
        double  data;       // data
        Node*   next;       // pointer
    };

    class List {
    public:
        List(void) { head = NULL; } // constructor
        ~List(void);                // destructor

        bool IsEmpty() { return head == NULL; } //boş kontrolü
        Node* InsertNode(int index, double x);  //node ekle
        int FindNode(double x);  //node bul
        int DeleteNode(double x); //node sil
        void DisplayList(void); //liste görüntüle
    private:
        Node* head; //baş kısmı
    };

    Node* List::InsertNode(int index, double x) {

        if (index < 0) return NULL; 

        int currIndex   =   1;
        Node* currNode  =   head;
        while (currNode && index > currIndex) {
            currNode    =   currNode->next;
            currIndex++;
        }
        if (index > 0 && currNode == NULL) return NULL;

        Node* newNode   =   new Node;
        newNode->data   =   x;  
        if (index == 0) {
            newNode->next   =   head;
            head        =   newNode;
        }
        else{
            newNode->next   =   currNode->next;
            currNode->next  =   newNode;
        }
        return newNode;
    }


    int List::FindNode(double x) {
        Node* currNode  =   head;
        int currIndex   =   1;
        while (currNode && currNode->data != x) {
            currNode    =   currNode->next;
            currIndex++;
        }
        if (currNode) return currIndex;
        return 0;
    }
    int List::DeleteNode(double x) {
        Node* prevNode  =   NULL;
        Node* currNode  =   head;
        int currIndex   =   1;
        while (currNode && currNode->data != x) {
            prevNode    =   currNode;
            currNode    =   currNode->next;
            currIndex++;
        }
        if (currNode) {
            if (prevNode) {
                prevNode->next  =   currNode->next;
                delete currNode;
            }
            else {
                head        =   currNode->next;
                delete currNode;
            }
            return currIndex;
        }
        return 0;
    }

    void List::DisplayList()
    {
       int num      =   0;
       Node* currNode   =   head;
       while (currNode != NULL)
       {
        printf("\n%lf",currNode->data);

        currNode    =   currNode->next;
        num++;
       }
       printf("\nNumber of nodes in the list: %d",num);
    }
    List::~List(void) {
       Node* currNode = head, *nextNode = NULL;
       while (currNode != NULL)
       {
        nextNode    =   currNode->next;
        // destroy the current node
        delete currNode;    
        currNode    =   nextNode;
       }
    }

    int main(int argc, char** argv) {

        List list;
        list.InsertNode(0,5.4); //başarılı
        list.InsertNode(1,6.5); //başarılı
        list.InsertNode(-2,5.5);//başarsız
        list.InsertNode(2,10.0);//başarılı
        list.DisplayList();
        list.DeleteNode(5.4);
        list.DisplayList();
        return 0;
    }

Now edit node part

class Node {
public:
    int no;
    char name[15];
    char surname[15];
    int age;
    Node* next; 
};

and insert function. Flow chart is here.

Node* List::InsertNode(int index, int no,char name[15],char surname[15],int age){
    if (index < 0) return NULL;
    int currIndex = 1;
    Node* currNode = head;
    while (currNode && index > currIndex) {
        currNode = currNode->next;
        currIndex++;
    }
    if (index > 0 && currNode == NULL) return NULL;
    Node* newNode = new Node;
    newNode->no = no;
    strcpy_s(newNode->name, name);
    strcpy_s(newNode->surname, surname);
    strcpy_s(newNode->age, age);
    if (index == 0) {
        newNode->next = head;
        head = newNode;
    }
    else {
        newNode->next = currNode->next;
        currNode->next = newNode;
    }
    return newNode;
}
Erkan Liman
  • 19
  • 1
  • 5
  • While this code may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) of how and why this solves the problem would really help to improve the quality of your post. Remember that you are answering the question for readers in the future, not just the person asking now! Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. – Makyen Apr 05 '17 at 22:45
  • @Makyen I've started using StackOverflow yet. So I answered late. thank you for your interest. I will pay attention to the rules. – Erkan Liman Apr 05 '17 at 23:14