Sunday, August 2, 2009

Need help with the last line using c i keep getting an error?

#include %26lt;stdio.h%26gt;


#include %26lt;string.h%26gt;


#include %26lt;ctype.h%26gt;





// Our function declaration saying it takes one string pointer and returns one string pointer.


char * flipstring(char *stringtoflip);





int main() {


// Strings to hold our lines (forward and backward)


char string[256];


char flipped[256];





// Our file pointers (one in and one out)


FILE * infile;


FILE * outfile;





// Open files to valid txt files


infile = fopen("input.txt","r");


outfile = fopen("output.txt","w");





// Loop through the input file reading each line up to 256 chars


while (fgets(string,256,infile) != NULL) {


printf("The value read in is: %s\n", string);





// Flip the string and copy it to our "flipped" string


strcpy(flipped,flipstring(string));





// Write "flipped" to output


printf("The value written is: %s\n",flipped);


fputs(flipped,outfile);


}

Need help with the last line using c i keep getting an error?
This is a good warning, it could cause a crash to return the address of a local variable, because when the funtion terminates the local variables terminate with them. Static variables can be used to illiminate this problem.





You could also instead of returning the string, accept a pointer to a string as an argument.





But remember, when a local variable is allocated into memory, it is only in memory while the function is running. Once the function stops, the memory is erased and your pointer is no longer valid.
Reply:Declaring reverse[256] as global should do it, but then I get seg fault.





#include%26lt;....%26gt;


#include%26lt;....%26gt;


...





char * flipstring(char *stringtoflip);


char reverse[256]; //Now this is global, not local





int main()


{





//Stuff





return 0;


}








char * flipstring(char *stringtoflip)


{





/*same, just remove the line "char reverse[256]" as it has been done earlier*/


........


.......


....


return reverse; //this time reverse is global not local


}








But I get a seg fault, probably there is some more errors in this code.


No comments:

Post a Comment