Caroline said:
Thank you all for your help.
Please stop top-posting. It's rude.
The following gave me the result I wanted on the first iteration:
char *nameOfFile;
char *ext ;
char *prefix;
nameOfFile ="";
This spells trouble later on. You should never assign a string literal
to a (non-const) pointer. String literals may not be modified, so you
should *only* use const pointers to point to a string literal.
sprintf(nameOfFile, "%s%d.%s", prefix, SomeNumber, ext);
This is a serious error that will be caught by the compiler if you
follow my advice above. nameOfFile points to a string literal, so you
are attempting to write your output over that string literal. This gives
undefined behavior. Even if string literals happen to be modifiable on
your implementation, you'll probably write past the end of the array.
...
but when I the function executed again, similar results appeared.
1 - How can I reset the variables at each iteration?
I don't know what you mean by that.
2 - How (and why) would MALLOC be used in this case?
malloc() is really only used in one way - it is called to allocate a
chunk of memory. The reason you might want to do that is because you
might only be able to determine how much memory you need at run-time
(not at compile-time).
You need an array to store the sprintf output into. You are currently
trying to use a string literal, which is not appropriate. You could
declare your array like this:
char nameOfFile[N];
But in order to do so you need to know an appropriate value for N when
you write the source. If you *don't* know how large the array needs to
be, but you can calculate it at run-time, you can do this instead:
char *nameOfFile;
size_t nameLength = /* calculate length here */;
nameOfFile = malloc(nameLength * sizeof(*nameOfFile));
if (nameOfFile != NULL)
{
sprintf(nameOfFile, "%s%d.%s", prefix, SomeNumber, ext);
}
else
{
/* handle allocation error */
}
-Kevin