UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C
  • » another way of writing a function which returns char*

#1 2009-05-22 01:29 PM

rvan
Member
Registered: 2009-02-27
Posts: 13

Re: another way of writing a function which returns char*

Hi All,

If we have function say

char* fun()
{
.
.
.
}



is there any other way of representing the return type which is equivalent to char*?


Thanks

Offline

#2 2009-05-22 01:52 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: another way of writing a function which returns char*

What do you mean?

Offline

#3 2009-05-22 02:36 PM

rvan
Member
Registered: 2009-02-27
Posts: 13

Re: another way of writing a function which returns char*

Offline

#4 2009-05-22 04:50 PM

jfriesne
Administrator
From: California
Registered: 2005-07-06
Posts: 348
Website

Re: another way of writing a function which returns char*

It sounds like you are asking if it is possible to do this:

char[5] MyFunc()
{
   char[5] x = "blah";
   return x;
}

According to g++, anyway, that is an error:

$ g++ temp.cpp 
temp.cpp:3: error: expected unqualified-id before ‘[’ token

So I think the answer is no.  You must return a char pointer, not a char array.  (Better yet, you could return an std::string or some other kind of String object, and avoid all the hassles involved with trying to manage memory directly)

Offline

#5 2009-05-22 06:55 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,839
Website

Re: another way of writing a function which returns char*

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

typedef struct mystr {
    char buf[1024];
} mystr;

mystr crap (void)
{
    mystr str;
    strcpy (str.buf, "Hello, world!");
    return (str);
}

int main ()
{
    mystr str = crap();
    printf ("%s\n", str.buf);
    return (0);
}

Offline

#6 2009-06-09 05:04 PM

Uzume
Administrator
Registered: 2002-08-30
Posts: 186

Re: another way of writing a function which returns char*

Offline

#7 2009-06-09 05:15 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,839
Website

Re: another way of writing a function which returns char*

#include <stdio.h>
#include <string.h>

void ugh (char str[])
{
    strcpy (str, "ugh");
}

int main ()
{
    char    buf[1024];

    strcpy (buf, "Blah");
    ugh (buf);
    printf ("%s\n", buf);

    return (0);
}

Offline

  • Index
  • » C
  • » another way of writing a function which returns char*

Board footer

Powered by FluxBB