So I've been new in structures so i tried to sort it like normal
bubble sort but it won't work and also ti gives me error like
"assignment with expression to array type"
I won't speak to what your code is actually trying to achieve but I will address the error you are getting. The compiler should be pointing out these two lines:
k[s].name= k[s+1].name;
k[s+1].name= pom;
So for clarity sake let's point out the fact that k
is an array of kokteli
structs and those structs contain members that are arrays (name
, sast1
, etc). k[s].name
and k[s+1].name
are both an array of char which in C is not assignable. You can modify the elements (char
) of the array via pointers to the memory address for each char
in the array. You would do that like this:
k[s].name[n] = //where n is an integer from 0 to 20, assign value of nth element here)
Let's break this statement down:
- k is a pointer to an array of
kokteli
structs
k[s]
is actually a pointer to the address of the kokteli
struct located at the memory address offset from k
by s
(the exact same thing in C as (k+s)
)
k[s].name
is actually a pointer to the address of the member name
of the kokteli
struct located at offset s
(can also be written in C as (k+s)->name
or &k[s] //since the first member is name
)
k[s].name[0]
is the contents of the 0th element of the member name
of the kokteli
struct located at the memory address offset from k
by s
(can also be written in C as *(k+s)->name
)
This is why the compiler doesn't complain about this line:
pom = k[s].name;
Now the caveat here is that the name of an array in C actually refers to a memory address for the beginning of the contents of that array. This means that it is a pointer itself. So since pom
and k[s].name
are actually both char *
, pom
now points to what k[s].name
is pointing at.
Your if clause here:
if(k[s].name > k[s+1].name){
...
}
Is actually comparing memory addresses as k[s].name
and k[s+1].name
both point to the first element in the array. The difference is that one is located at a memory offset that is sizeof(kokteli)
greater than the other (that is k[s+1].name
) so this statement will never be true
. I've made some code for you here that will nail this home.
As other people in the comments have pointed out, you will actually want to use strcmp (need to #include <string.h>
) to compare the elements of the two arrays of type char
. Reference for strcmp is located here.
So your if clause should look something like this
if(strcmp(k[s].name, k[s+1].name) > 0){
//k[s].name comes after k[s+1].name alphabetically
}
For more on how strcmp works, see this answer.