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));
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));
strcpy(string1, string2);
return string1;
}
int main (void)
{
char *string;
string = somefunction();
printf ("\n\nString is: %s\n\n", string);
return 0;
}
Coding 3.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *
somefunction()
{
char *string2 = "some words";
return string2;
}
int main (void)
{
char *string;
string = somefunction();
printf ("\n\nString is: %s\n\n", string);
return 0;
}
Hope this helps.
O Plameras
ashley maher wrote:
G'day,
I know this is not even C 101 level but would some kind soul please
explain to me why this is not even close to working.
Regards,
Ashley
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int somefunction(char *string1)
{
char *string2 = "some words\0";
string1 = (char *)calloc(strlen(string2 + 1), sizeof (char));
strcpy(string1, string2);
return 0;
}
int main ()
{
char *string;
somefunction(string);
printf ("\n\nString is: %s\n\n", string);
free (string);
return 0;
}
--
SLUG - Sydney Linux User's Group Mailing List - http://slug.org.au/
Subscription info and FAQs: http://slug.org.au/faq/mailinglists.html