The array temp
exist only in the scope of function stringParser()
. The pointer t
points to the array temp
or in other words t
holds the address of where temp
is stored. When you return from the function stringParser()
, the array temp
does no longer exist and accessing it causes undefined behavior (UB). You return the pointer t
that points to temp
and give it to printf()
. printf()
dereferences the pointer, means it wants to access the array to which t
points to, but the array temp
does no long exist and therefore you have UB.
There are multiple ways to avoid UB:
- Make the array
temp
static
. But that does not work well with multi threading programs and should be avoided in libraries.
- Use dynamic memory allocation, reserve the storage for the
temp
-array with malloc()
or calloc()
, but then you have to free()
the memory again after you no longer need it.
- Declare the array inside
main()
and pass a pointer to it to stringParser()
, but keep the size in check and make sure you never get a buffer overflow.
Off-Topic: size_t
is a better type for array indexing, since it is guaranteed to be large enough to hold every possible index and size_t
is unsigned. Your program is prone to buffer overflows by future changes. Since you do not document that the string given to stringParser()
has to be shorter than 100 char
s. You need to document that better, check if the string is not too long or create the array dynamically to be big enough for the given string.