why can not use strcat() in below c code?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nilushika
    New Member
    • Sep 2013
    • 20

    why can not use strcat() in below c code?

    when I try to run this it throws a runtime error.
    Code:
    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    void savefile(char *p);
    int main(){	
    savefile("c proramming"); 
    }
    void savefile(char *p){
      	FILE*fp;
    	fp=fopen("result.txt","w");
    	if(fp==NULL){
    		printf("error");
    		exit(0);
    	}
    	strcat(p,"\n");//line A
    	fputs(p,fp);
    	fclose(fp);
    }
    but when i commented line A it runs.can't understand what is going wrong there.can you please help me?
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    You are using "c proramming" as your string to append to. This is a literal and is fixed in size. That is, it is a constant.

    You need to pass your function the address of a string that has a \0 already in it. A string you have created yourself.

    Code:
    char str[100];
    strcpy(str,"c proramming"); 
    savefile(str);

    Comment

    Working...