Benno wrote:

On Tue Nov 22, 2005 at 16:16:29 +1100, O Plameras wrote:
Hi ashley,

I have three sets of codes that will do the task as I see it from your codes.
I presented these three codes from the least to the most preferred coding.

The common idea in all the three codes: 'somefunction' has static array
of characters that is to be printed in 'main'; to accomplish this, just pass that address of the
first character in a string to be printed. I changed the TYPE of
'somefunction' from 'int' to 'char *' to achieve this end.

I used malloc instead of calloc in Coding 2. It is sufficient in the context of your original codes.

Notice I did not use calloc or malloc in Coding 3 as I am just passing an address.

Coding 1. #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *
somefunction()
{
     char *string1;
     char *string2 = "some words\0";
     string1 = (char *)calloc(strlen(string2 + 1), sizeof (char));

Should be strlen(string2) + 1


Your are wrong. The string is "some words\0". there is no need for extra char.

     strcpy(string1, string2);
     return string1;
}
int main (void)
{
     char *string;
     string = somefunction();
     printf ("\n\nString is: %s\n\n", string);
     return 0;
}

Coding 2.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *
somefunction()
{
     char *string1;
     char *string2 = "some words\0";
     string1 = malloc(strlen(string2));

Should be strlen(string2) + 1


Your are wrong. The string is "some words\0". there is no need for extra char.

     strcpy(string1, string2);
     return string1;
}
int main (void)
{
     char *string;
     string = somefunction();
     printf ("\n\nString is: %s\n\n", string);
     return 0;
}

Moral of the story is don't code in C ;) Or if you do use as many tools
to help you as possible. -Wall, and a C linter are a good start.
Valgrind is also meant to be good, although I haven't
used it.

I don't understand this. Please explain.

Benno

--
SLUG - Sydney Linux User's Group Mailing List - http://slug.org.au/
Subscription info and FAQs: http://slug.org.au/faq/mailinglists.html

Reply via email to