user3361615
user3361615

Reputation: 1

How to keep linked list head from changing?

I'm trying to create a linked list structure to store data. The head of the linked list seems to be updating somehow. I have the following code. I can't seem to figure out how put char array data into a node and keep it from updating when the address to said char array's data updates.

The following code prints out whatever string is passed into the processStr function. How do I keep head from updating ?

//Linked List Structure 
mainNode *head = NULL;

//take and store word in data structure 
void processStr(char *str){

    //char array
   char strArray[sizeof(str)+1];

    //stores lower case string
    char strLower[strlen(str)];
    int i;
    for(i = 0; str[i]; i++)
            strLower[i] = tolower(str[i]);
    strLower[i] = '\0';

    //printf("%s : ", strLower);

    //Starts Linked List
    if(head == NULL){

            mainNode *mainPtr = (mainNode *)malloc(sizeof(mainNode));
            nameNode *namePtr = (nameNode *)malloc(sizeof(nameNode));

            mainPtr->name = strLower;
            mainPtr->numOccurances = 1;
            mainPtr->next = NULL;
            mainPtr->nextName = namePtr;

            namePtr->name = strArray;
            namePtr->next = NULL;

            head = mainPtr;

    }

    printf("%s : " , head->name);
}

Upvotes: 0

Views: 153

Answers (2)

Vineet1982
Vineet1982

Reputation: 7918

The above code will only run once only which will add information to head only once. If you want to add more information in case of second run then add code for else condition. Example:-

if ( head == NULL ) {

   // code to insert data in case of first run
}else{

   // code to insert data for second run and so.....
}

Upvotes: 0

Ingo Leonhardt
Ingo Leonhardt

Reputation: 9904

You assign the pointers mainPtr->name and namePtr->name to variables strLower and strArray that are declared locally in processStr(). That means after that function returns, any access to these pointers results in undefined behaviour. You could do sth. like

 mainPtr->name = strdup( strLower );

instead to allocate memory for the strings.

Btw.: strLower must also be declared as char strLower[strlen(str)+1];

Upvotes: 1

Related Questions