Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Returning char[] 2

Status
Not open for further replies.

mattias1975

Programmer
Jul 26, 2004
36
0
0
SE
Hello!

How do i return a char[] from a function?
Do i have return a pointer to it?
A smal example code would be nice.

Thank you.
 
You can't return an array of type char. You can return a pointer to an array, or you could (if you really wanted to), encase the array in a struct and return that. For the first option, you must return a pointer to either a local static variable, or one allocated outside of the function. You cannot return a pointer to an array allocated within the function (unless it was dynamically created, eg via malloc). Simple, eh!

I don't know what context you're doing this in, so here's one example of how it might be done.
Code:
#include <stdio.h>
#include <string.h>

char *foo(char *s)
{
  static char buffer[BUFSIZ];
  strcpy (buffer, s); /* Do buffer overflow checking! */
  return s;
}

int main(void)
{
  char name1[] = "fred";
  char name2[] = "bloggs";
  char *p;
  
  p = foo(name1);
  puts (p);
  p = foo(name2);
  puts (p);
  
  return(0);
}
or
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *foo(char *s)
{
  char  *p;

  if ((p = malloc(strlen(s) + 1)) != NULL)
  {
    strcpy(p, s);
  }

  return(p);
}

int main(void)
{
  char  name1[] = "fred";
  char  *p;

  if ((p = foo(name1)) != NULL)
  {
    puts(p);
  }

  free(p);

  return(0);
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top