Passing Strings
Jul 14, 2018 at 8:14am UTC
Attempting to make a timestamp program where the current time is printed to a text file when the program is run.
Wanting to keep the code modular, I wanted to separate the code into functions. Despite the use of pointers, the "printToFile" function prints (null) when run in main.
What is going wrong?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void printToFile(char * strTime);
void getTimeString(char * strTime) {
time_t currentTime;
struct tm* myTime;
time(¤tTime);
strTime = ctime(¤tTime);
printf("%s\n" , strTime);
printToFile(strTime);
}
void printToFile(char * strTime) {
FILE* fp;
fp = fopen("time.txt" , "a" );
fputc('\n' , fp);
fprintf(fp, "%s\n" , strTime);
fclose(fp);
}
int main(void ) {
char * strTime;
getTimeString(strTime);
// printf("%s\n", strTime); // gives core dump
// printToFile(strTime); // prints "(null)" to file
return EXIT_SUCCESS;
}
Jul 14, 2018 at 8:22am UTC
The pointer is passed by value so the function receives a copy of the pointer and any changes to the copy inside the function will not affect the original pointer in main.
Jul 14, 2018 at 9:57am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void printToFile(char * strTime);
char * getTimeString()
{
time_t currentTime;
// struct tm* myTime;
time(¤tTime);
char * strTime = ctime(¤tTime);
printf("%s\n" , strTime);
printToFile(strTime);
return strTime;
}
void printToFile(char * strTime)
{
FILE* fp;
fp = fopen("time.txt" , "a" );
fputc('\n' , fp);
fprintf(fp, "%s\n" , strTime);
fclose(fp);
}
int main(void )
{
char * strTime = getTimeString();
printf("%s\n" , strTime);
return 0;
}
Jul 14, 2018 at 3:02pm UTC
@Peter87
I thought content in the pointer was passed by reference? The pointer it's self is passed by value right?
@FurryGuy
I'll try this out later today
Topic archived. No new replies allowed.