Perhaps the fortran function below I am trying to translate to C
will explain further, (note no MALLOC is required)..
Well, apparently the Fortran function below *doesn't* help; not
enough, anyway, because you've posted it twice now and I don't
think anyone's really solved your problem. So maybe you should
try to explain your question in one of the languages more commonly
used on this newsgroup, such as C or English. (Heck, German would
probably get the job done, too, but it wouldn't be as welcomed as
English. ;-)
I'm going to try to decode your program anyway, and you can tell
me if I get it right.
program varying_string_output
write (*,*) enclose('123'),',' ! outputs "123",
Since writing a C program to output "123" is trivial, I assume
you're wanting to write a C function that takes a string such as
'123' and encloses it in quotes: '"123"', like that.
write (*,*) enclose('the lazy dog'),',' ! outputs "the lazy dog",
stop
contains
function enclose(s1) result(s2)
character(*) :: s1
character(len_trim(s1)+2) :: s2 ! output length = input length+2
s2 = '"' // trim(s1) // '"' ! enclose "string" in quotes
I don't know what 'trim(s1)' does, but I'll assume that 'trim' is
a no-op in this context.
So three ways of doing this are
/* Fails if the user passes a 'src' longer than MAX_STRING_LENGTH;
* each call overwrites the old string */
const char *enclose(const char *src)
{
static char buffer[MAX_STRING_LENGTH];
if (strlen(src)+3 > sizeof buffer)
return NULL;
sprintf(buffer, "\"%s\"", src);
return buffer;
}
/* Undefined behavior if the user passes an invalid 'dst' */
char *enclose(const char *src, char *dst)
{
sprintf(dst, "\"%s\"", src);
return dst;
}
/* Fails if malloc fails; user must free() the supplied string */
char *enclose(const char *src)
{
char *p = malloc(strlen(src)+3);
if (p != NULL)
sprintf(p, "\"%s\"", src);
return p;
}
Note that in *none* of these cases can you write
printf("%s %s\n", enclose("abc"), enclose("def"));
and have it work correctly. In Case 1, you get unspecified
behavior because both calls to 'enclose' are trying to write
on the same chunk of memory. In Case 2, you just flat out are
supplying the wrong number of arguments. And in Case 3, it works
just fine -- but you have a memory leak because you never 'free()'
the allocated strings. The correct use of each function might be
/* Case 1 */
printf("%s ", enclose("abc")); /* get a semicolon between them */
printf("%s\n", enclose("def"));
/* Case 2 */
char p[4], q[4];
printf("%s %s\n", enclose("abc", p), enclose("def", q));
/* Case 3 */
char *p = enclose("abc");
char *q = enclose("def");
printf("%s %s\n", p, q);
free(p);
free(q);
Which of these methods you use depends on your personal style
and the convenience of each of them for your particular project.
HTH,
-Arthur