Passing Strings

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(&currentTime);
    strTime = ctime(&currentTime);
    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;
}
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.
closed account (E0p9LyTq)
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(&currentTime);
   char* strTime = ctime(&currentTime);
   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;
}
@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.