views:

116

answers:

7

I have 1 function that I want to return the address of an assigned string to the main function and assign an new string pointer with the same address so that the new string will have the contents of the old string.

For example:

 unknown_datatype function()
 {
      char *old = "THE STRING";
      return old;
 }

 int main()
 {
      char *snew = "";
      snew = function();
      return 0;
 }

*unknown_datatype means I don't know that to put there...

*How can I approach this without changing anything in the main() method

+1  A: 

You can simply return a char*. Since you are returning a pointer to a string literal, it's probably best to return a const char*, since you aren't able to modify the string literal:

const char* function()

And likewise you would want to assign the return value to a const char*:

const char* snew = 0;
snew = function();
James McNellis
I get this [Warning]: assignment makes pointer from integer without a cast
Y_Y
Probably `function` is declared below this line. If the C compiler does not have a declaration for a function that you are calling when it encounters the call, it assumes that the function returns `int`. You need to create a prototype for your function that precedes the line where you call `function`.
Tyler McHenry
+3  A: 

Typically you will pass the address of the first element in an array of chars in, as well as the length, and have the function fill it.

int fillMyString(char *str, int buffer_size)
{
  if(buffer_size > strlen("test"))
  {
    strncpy(str, "test", buffer_size-1);
    str[buffer_size-1] = '\0';
    return strlen(str);
  }

  return 0;
}


//In some function or main
char buffer[1024];
fillMyString(buffer, 1024);
ASSERT(!strcmp(buffer, "test"));

Edit: You mentioned that for some reason you need to return a char*. I would suggest in that case to use malloc to allocate the string inside the function, but make sure whenever you call the function you free the return value eventually.

Brian R. Bondy
+1 for passing in the buffer... otherwise, you have ambiguous ownership or non-reentrance. Passing in a buffer allows the function to be non-reentrant and makes it clear who is responsible for allocation/deallocation.
Michael Aaron Safyan
-1 for not passing in the size of the buffer. You are risking buffer overflow!
Michael Aaron Safyan
It make sense your way and thats the way I been doing it since... But is the assignment I have that doesn't let me change main function so I have to assign it like main says.
Y_Y
@Michael: I did, think you wrote that as I was editing.
Brian R. Bondy
I guess I'll have to break the rules
Y_Y
@Brian, now that you've edited it, I've given you your +1 back.
Michael Aaron Safyan
Or...return a pointer to the buffer that you're given, like strcpy() et al do.
Jonathan Leffler
Also, if you're going to use 'strncpy(str, "test", len-1)', make sure of the null termination by doing `buffer[len-1] = '\0';`. Nominally, you should ensure len > 0 too before doing anything.
Jonathan Leffler
@Jonathan: You're right thanks, just in case the string is >= than the passed in length. Corrected.
Brian R. Bondy
sizeof("test") == sizeof(char *)you should have local variables s="test" and l=strlen(s);
drawnonward
@drawnonward: yes of course, someone modified my answer to put that. Fixed it.
Brian R. Bondy
A: 

The unknown data type would have to be char* but in this case it would not do what you expect since the variables in function() are local variables that will disappear once the function exits and they get popped off the stack. You could use a malloc() call inside the function and return a pointer to the new string. Just don't forget to free it when you're done with it.

Fred
String literals have static storage duration, so a pointer to the string literal `"THE STRING"` is valid after the function returns (the lifetime of the string literal is the lifetime of the program).
James McNellis
It is a fine point of detail that although the pointer to the data in the function is destroyed, the string literal that it pointed at probably still exists, unchanged. I'm not certain whether the C Standard speaks to that. Your comment would be 100% valid if the declaration in the function was `char old[] = "THE STRING";`.
Jonathan Leffler
@Jonathan: When you say "comment," are you referring to Fred's answer or to my comment to the answer?
James McNellis
@James: well, I was making the same point as you made at the same time you were making your comments. When I said 'repeat' against my comment to Romain's answer, I was repeating the comment I'd made against Fred's answer - and after I'd submitted, I found you had also made roughly the same comment as me against the same two answers. So, lots of repetition - by me, and by you.
Jonathan Leffler
@Jonathan: Ok; sorry, I was just confused :-).
James McNellis
A: 
Michael Aaron Safyan
Make sense Like I reply to him but I need to make it work without passing any parameters... (I cannot change the main() method meaning I cannot pass parameters)
Y_Y
@Y_Y, you will need to change the main function, anyway, to call "free".
Michael Aaron Safyan
A: 

OK here is the answer: Since I cannot EDIT the main (MEANING I CANNOT PASS ANY PARAMETER) the following solution is possible:

char *function()
{

    char *old;
    old = (char*)malloc(9999);
    strcpy(old,"THE STRING");
    return old;
}

int main()
{
    char *snew = "";
    snew = function();
    return 0;
}

Thanks for all who replied.

Y_Y
@Y_Y, that solution leaks. Now, that may be fine because it is main, but for any other function, that would not be a valid solution.
Michael Aaron Safyan
True, But for the given project or assignment I know the user will have to limit their input to 3 characters so '9999' is a little too much... I understand where u r coming from but for the given problem, I think that is a fair solution
Y_Y
The waste of memory: Blame it on my teacher!!!!
Y_Y
Since `function` never returns anything else, it could just return "THE STRING" directly or return a pointer to a static buffer.
jamesdlin
Yeah, if I post the entire code then it'll make sense why this method is the most wanted.
Y_Y
A: 
char * function()
{
    char *old = "THE STRING";
    return old;
}

int main()
{
     char *snew = "";
     snew = function();
     return 0;
}
sza
A: 

Your question and example are contradicting each other.

Is this what your looking for ? given below are two simple solutions.

char* func(char *);

int main()

{

char *newstring="Hey";

newstring = func(newstring);

printf("New string : %s\n", newstring);

}

char* func(char *s)

{

printf("Old string : %s\n", s);

s="Hello";

return(s);

}

or else the solution given by Y_Y is also fine, assuming your string is created in the function call. Just in case you do not want to use malloc, the solution below works.

char* func();

int main()

{

char *newstring="";

newstring = func();

printf("New string : %s\n", newstring);

}

char* func()

{

char *s="Hello";

printf("Old string : %s\n", s);

return(s);

}

Abhijit K Rao