Thread: Return string pointer help!!!!

  1. #1
    Registered User
    Join Date
    May 2013
    Posts
    1

    Return string pointer help!!!!

    if you have something like this how can you print the string in main??

    Code:
    /#include <stdio.h>
    #include <stdlib.h>
    void myf(char *p)
    {
        p="balls";
    }
    int main()
    {
      int i=0,j;
      char ch[10];
      myf(ch);
      for(i=0;i<10;i++) printf("%c",ch[i]);
      printf("\n");
      system("PAUSE");
      return 0;
    }

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    p is just a copy of ch in main. it's value is lost after return from myf().

    try
    Code:
    void myf(char *p)
    {
          strcpy( p, "balls" );
    }
    to make the function safe you should pass the size of the buffer as well and use strncpy().

    Kurt
    Last edited by ZuK; 05-23-2013 at 11:35 AM.

  3. #3
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    since you are passing the address of a char array, you need to copy the string into it in myf. p is local to myf, so changing it in your function doesn't affect any value in main. but p is pointing at the char array 'ch' so you can copy data to where it is pointing.
    Code:
    void myf(char *p)
    {
          strcpy(p,"balls");
    }

    however you usually would want to pass in the length of the destination array and use strncpy to avoid accidental overruns.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to return address of a pointer?
    By spotty in forum C Programming
    Replies: 1
    Last Post: 02-11-2010, 08:11 PM
  2. Replies: 1
    Last Post: 07-04-2007, 12:20 AM
  3. Replies: 6
    Last Post: 04-09-2006, 04:32 PM
  4. Return Pointer Deallocation
    By vasanth in forum C++ Programming
    Replies: 7
    Last Post: 08-06-2003, 12:15 PM
  5. Replies: 5
    Last Post: 06-03-2002, 08:47 AM