PDA

View Full Version : Mysterious C Syntax Error


willz99ta
06-29-2004, 12:28 AM
Everytime I try to press Go to execute the program, it says:

Unhandled exception in concatenator.exe: 0xC0000005: Access Violation

I think the logic is right, and I think the problem is with C being able to accept and concatenate the "~" character. :confused:


Hell I just don't know. I just need it to say "~" (the last character in my text file) and "World"

Thanks for any help you have
Will Howard


Here is the code:
----------------------------------------------------------

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {

char *str1;

char *str2 = "World";
char *str3;
char c,lc;
int num;

FILE *fp;

fp = fopen("example/input.txt", "r");


if(fp==NULL) {
printf("Error: can't open file.\n");
return 1;
}

while(1) { /*loop*/
lc=c;
c = fgetc(fp);

if(c!=EOF) {
printf("%c", c);
}

else {
break; /* ...break when EOF is reached */
}
}




str1 = lc;


num=sizeof(str1) + sizeof(str2) + 1;
printf("length %d\n", num);
str3 = (char *)calloc(num, sizeof(char));

strcpy( str3,str1);
printf("str3: %s\n", str3);
strcat(str3, str1);
strcat(str3, str2);

printf("Concatenation: %s\n", str3);

free(str3);


printf("File concatenated. Now closing the file\n");

fclose(fp);

return 0;

}

shmoove
06-29-2004, 09:06 AM
str1 = lc;

str1 is a pointer and you are setting it to the value of the last character. So it will point to a memory address equal to the ASCII value of the last character, and not to a string that has your last character which is what you want. That's what's causing the access violation when you try to dereference str1.

shmoove

willz99ta
06-29-2004, 04:22 PM
How would you fix the problem and still use pointers?

Will Howard

shmoove
06-29-2004, 05:53 PM
You have to allocate memory for str1 and then place the char in there, plus a null terminator:

str1 = (char *)calloc(2, sizeof(char)); // one for the char and one for '\0'
str1[0] = lc;
str1[1] = 0;


shmoove

willz99ta
06-29-2004, 06:06 PM
Thanks for your help Shmoove, you've been a lifesaver.

Will Howard