Question

So i have a struct that has name and age. Look inside the displayRecords() under main, there I am trying to bubble sort array of structs by age. I am able to sort the age, but i am having trouble simultaneously sorting the sting called name[100] to correspond to the correct age. When i try to set it equal to something, for example a[j+1].name= a[j].name it gives me the error: expression must be a modifiable variable. I think i tried everything from using -> to even putting putting parentheses in various places. *a[j+1].name= *a[j].name worked but it only sorted the first letter in the string.

Below is the problem at hand, look inside the displayRecords() function

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define pause system("pause")
#define cls system("cls")
#define SIZE 10


typedef struct{
    char name[100];
    int age;
}THING;


main(){
    THING thing[SIZE];
    defaultValue(thing);
    displayRecords(thing);

}//End main 

void displayRecords(THING a[]){
    int i, j;
    int temp;
    char* temp2;


    for(i=0; i<SIZE; i++)
    {
        for(j=0; j<SIZE-1; j++)
        {
            if(a[j].age>a[j+1].age)
            {
                temp = a[j+1].age;
                temp2= a[j+1].name;

                a[j+1].age = a[j].age;
                a[j+1].name= a[j].name;

                a[j].age = temp;
                a[j].name= temp2;
            }
        }

    }//end bubble sort

    for(i=0;i<SIZE;i++){
        printf("\n%s is %i\n",a[i].name,a[i].age);
    }//end for
    pause;
}//end display records



void defaultValue(THING a[]){
    strcpy(a[0].name, "Dennis");
    strcpy(a[1].name, "Willie");
    strcpy(a[2].name, "Tammy");
    strcpy(a[3].name, "Abbie");
    strcpy(a[4].name, "Spike");
    strcpy(a[5].name, "Willis");
    strcpy(a[6].name, "Frankie");
    strcpy(a[7].name, "Betty");
    strcpy(a[8].name, "Donna");
    strcpy(a[9].name, "Abe");
    a[0].age=45;
    a[1].age=22;
    a[2].age=99;
    a[3].age=75;
    a[4].age=5;
    a[5].age=4;
    a[6].age=67;
    a[7].age=36;
    a[8].age=11;
    a[9].age=21;
}//end defaultvalue
Was it helpful?

Solution

You can't assign to arrays, only initialize them on definition. You can however copy to them, like with strcpy.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top