samedi 25 avril 2015

Segmentation fault while using array of char arrays


i have C program. It compiles and works fine, without errors, gives proper results, but when i run debugger, i get segmentation fault. I'm advised to solve this issue, but i don't know whats wrong.

This causes problems:

char names[20][20]; //is this correct?

for(i=0;i<20;i++)
{
    strcpy(names[i],base[i].name);
}

for(i=19;i>=0;i--)
{
    for(j=0;j<i;j++)
    {
        if(strcmp(names[j],names[j+1])>0)
        {
            strcpy(temp,names[j]);
            strcpy(names[j],names[j+1]);
            strcpy(names[j+1],temp);
        }
    }
}

Those elements in base[i].name are:

char name[20];

base = (person*) malloc(20 * sizeof(person));

Generally speaking, all of involved structures have length 20, so I don't know what I'm doing wrong. I guess I'm trying to access memory which I shouldn't, but where?


Aucun commentaire:

Enregistrer un commentaire