简体   繁体   中英

illegal hardware instruction error when concatenating two strings in c

I want to loop through a text file and concatenate all the strings until a blank line is hit and then do the same for the next strings and so on. The result of each string concatenation should be added to an char* array:

char* element_arr[287];

void splitPassports(FILE* file_to_read){
     char element[500];
     char str[80];
     int i = 0;
     int j = 0;

     while(j < FILELENGTH){
         if (fgets(str,80, file_to_read) && !isBlank(str)){
             strcat(element,str);
             printf("The string is: %s\n",str);
         }else if (isBlank(str)){
             element_arr[i] = element;
             memset(element, '\0', sizeof element);
             printf("%s\n",element_arr[0]);
             i++;
         }
         j++;
     }

     fclose(file_to_read);
 }

However when I try to do this I get an illegal hardware instruction error (I'm on a Mac). How can I properly add the new strings to the existing one and then append that to my array and after that set it back to zero to do the same for the few lines until a blank line is hit? I'm relatively new to C so thanks in advance:)

  1. char element[] = ""; you declare the array which is 1 char long, so the strcat will always fail (unless the second string is also empty).

  2. Even if you define it the correct way, the assignment element_arr[i] = element; you will assign the array element with the same reference every time, so the array will be simple filled with references to the same object.

  3. while(!feof(file_to_read)) - read Why is “while (?feof (file) )” always wrong?

I would recommend starting with the C book as you do not understand the basics of the language.

Dumb response to question 3, you could see if the problem is due to over-layering. I am also a Mac user, and my code will sometimes have errors occur due to having too many layers of functions etc. I don't know if anyone has already found the answer to question 3, however I genuinely hope this helps/helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM