2

program automatically exits at this point, so i presume the mistake is on this code:

 for(k=0; k<cc; k++){
     smallest = k;
     for(j=k+1; j<cc; j++){
         if (strcasecmp(pb[k].name, pb[j].name)>0){
                smallest = j;
         }
     }
     swapString(pb[k].name, pb[j].name);
  }

the following are my initial declarations:

void swapString(char string1[], char string2[]){
    char temp[31];
    strcpy(temp, string1);
    strcpy(string1, string2);
    strcpy(string2, temp);
}

typedef struct myphonebook{
char name[31];
char address[101];
char cellphone[11];
char email[21];
} Myphonebooktype;

int main (int argc, char * argv[]){
Myphonebooktype*pb = NULL;

FILE*fp;

char username[16];
char password[16];
char option;
int i, k, j, cc, smallest;

is strcmp wrong? or i cannot compare strings inside struct? my goal is to sort my struct alphabetically. update: sorry, my mistake, it should be k

4
  • In your for loop which says for(k=0; i<cc; k++){ did you mean to use i rather than k? I.e. did you mean for(k=0; k<cc; k++){ Commented Feb 3, 2014 at 14:43
  • 2
    You don't even use the value of smallest. Commented Feb 3, 2014 at 14:45
  • swapString(pb[k].name, pb[j].name); meant swapString(pb[0..cc-1].name, pb[cc].name);, Commented Feb 3, 2014 at 14:47
  • tnx, you're also correct, i should have used the smallest when i used the swap function. Commented Feb 3, 2014 at 15:01

1 Answer 1

2

Looks like a simple typo in your outer for loop:

for(k=0; i<cc; k++){

Should be k<cc I think? This error is probably causing an "infinite loop," but as soon as k reaches cc you're indexing past the end of the array, which is undefined behavior (explains your program crashing).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.