Returning Pointers - need some help

This is a discussion on Returning Pointers - need some help within the C Programming forums, part of the General Programming Boards category; Hello - I'm new to C programming (yes I have a book) and I've been working on a little project, ...

  1. #1
    Registered User
    Join Date
    Aug 2004
    Posts
    2

    Returning Pointers - need some help

    Hello - I'm new to C programming (yes I have a book) and I've been working on a little project, which is a laptop deamon. It does some functions I need to monitor the health of my laptop. But that's besides the point (lol I love puns!). I'm trying to clean up some code - which takes a string and gets rid of all spaces.

    Code:
    	for(k = 0; k <= strlen(StreamRead); k++)
    	{
    	  if(StreamRead[k] != ' ')
    	  {
    	    StreamClean[j] = StreamRead[k];
    	    j++;
    	  }
    	}
    That's it. Well I want to put this into a function to clean up my code (and make it more readable). But I've become lost at how to return pointers. I'm thinking of creating a function that would be run with CleanStream(StreamRead);. Similiar to strcmp(str1,str1), etc.

    Here's where I'm at now:

    Code:
    char * CleanStream(const char * Str)
    {
      char StreamClean[128];
      char *ptrClean;
    
    	for(k = 0; k <= strlen(Str); k++)
    	{
    	  if(Str[k] != ' ')
    	  {
    	    StreamClean[j] = Str[k];
    	    j++;
    	  }
    	}
    
      ptrClean = &StreamClean;
      return ptrClean;
    }
    So the whole idea would be ptrClean would return the location of StreamClean. But I don't know if the code works I wrote it by reading some source of some other codes. The second part which I don't understand is how to I set a variable to equal the data at the memory? Would something like StrSomevar = CleanStream(StreamRead); suffice?


    Have a good nigth (it's 12:51 right now),


    -servo

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You can't return 'StreamClean', or a pointer to it, and expect to use it, because 'StreamClean' goes out of scope when the function ends. Either:
    a) Make it static
    Code:
    static char StreamClean[FOO];
    
    ...
    
    return StreamClean;
    Which will preserve its scope, or:
    b) Use malloc to dynamicly allocate memory you need, and return that. If you do so, you'll need to free said allocated memory when you're through with it:
    Code:
    char *StreamClean;
    
    StreamClean = malloc( SOME_AMOUNT );
    
    return StreamClean;
    There are other interesting bits regarding the use of static, but I'll let you figure those out for yourself.

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    No need for another array if you can change the array that is passed in
    Code:
    char * CleanStream(char * Str )
    {
      char *j, *k;
      for ( j = k = Str; *k != '\0'; k++)
        if ( *k != ' ' )
          *j++ = *k;
      *j = '\0';
      return Str;
    }

  4. #4
    Registered User
    Join Date
    Aug 2004
    Posts
    2
    Quote Originally Posted by quzah
    b) Use malloc to dynamicly allocate memory you need, and return that. If you do so, you'll need to free said allocated memory when you're through with it:
    Code:
    char *StreamClean;
    
    StreamClean = malloc( SOME_AMOUNT );
    
    return StreamClean;
    There are other interesting bits regarding the use of static, but I'll let you figure those out for yourself.

    Quzah.
    How would I free the memory? If in a function I call someothervar = CleanStream(somevar); the memory is allocated in the CleanStream function. So wouldn't I have free() the memory outside of the CleanStream function because if I freed it inside the function then it would not return anything useless?

    Thanks for the help =-)

  5. #5
    C Programmer Stack Overflow's Avatar
    Join Date
    Apr 2004
    Posts
    477
    How would I free the memory?
    Well, as you may know, its a pointer. So you can free it anywhere you want, as long as its allocated. The reason is, pointers point to a memory address, no matter where your programs state is. For example:

    Code:
    char* foo(void) {
    	char *ptr; // just a pointer to nothing
    
    	ptr = (char *)malloc(25); // point to something
    
    	strcpy(ptr, "This is a pointer"); // write to the memory
    
    	return ptr; // return this memory address
    }
    
    int main() {
    	char *p; // just a pointer to nothing
    
    	p = foo(); // pickup the memory address, and set it to p
    
    	free(p); // ptr [mask of p] now frees
    
    	return 0;
    }

    Hope that makes sense,
    - Stack Overflow
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  6. #6
    Registered User
    Join Date
    Dec 2002
    Posts
    35
    Personally most liked Thantos' s advice. And as an alternative, dont return anything(void). And just use in func then use the same pointers later.

    CleanStream( pStr );
    printf(pStr); // now it is different
    Want to learn? Then try to teach...

  7. #7
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by fizisyen
    Personally most liked Thantos' s advice. And as an alternative, dont return anything(void). And just use in func then use the same pointers later.

    CleanStream( pStr );
    printf(pStr); // now it is different
    The problem, as hinted at by Thantos, occurs if I do this, with his function:
    Code:
    char * CleanStream(char * Str )
    {
      char *j, *k;
      for ( j = k = Str; *k != '\0'; k++)
        if ( *k != ' ' )
          *j++ = *k;
      *j = '\0';
      return Str;
    }
    
    
    int main( void )
    {
        char *p;
    
        p = CleanStream( "Watch me crash your program!" );
    
        return 0;
    }
    Quzah.
    Hope is the first step on the road to disappointment.

  8. #8
    Registered User
    Join Date
    Dec 2002
    Posts
    35
    yeah maybe you are right. I didnt tested any code this thread nor looked in to code, honestly. But i prefered because of working on pointer to original and returning the address approach. Surely, comparison to doing new arrays for this job. And at this manner, i am already thinking the same thing.

    And, as i said already didnt test the above code you pointed. But, i suppose it is because of algorithm error.

    Code:
        if ( *k != ' ' )
          *j++ = *k;
      *j = '\0';                   << here.
    i suppose this is the place. In the first loop, putting NULL behind original string 2. char. And not controlling char. Useless. Not acceptable behavior. Needing an "else" statement. I suppose so. Maybe later will test this.

    Regards
    Want to learn? Then try to teach...

  9. #9
    Registered User
    Join Date
    Dec 2002
    Posts
    35
    No i was wrong. Sorry. "j" is out of loop. Then i wonder why crashing.
    Want to learn? Then try to teach...

  10. #10
    Registered User
    Join Date
    Dec 2002
    Posts
    35
    No i was wrong. Sorry. "*j = '\0'" is out of loop. Then i wonder why crashing.
    Want to learn? Then try to teach...

  11. #11
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>Then i wonder why crashing.
    Because the original string is a string literal, which is most likely stored in read only memory.
    http://www.eskimo.com/~scs/C-faq/q1.32.html
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  12. #12
    Registered User
    Join Date
    Jun 2003
    Posts
    51
    you do not need to return any pointer
    if you do call by reference for both changed and unchanged pointees
    or simply apply the changes to the same pointee

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Double pointers and linked lists.
    By simo_r in forum C Programming
    Replies: 2
    Last Post: 05-06-2008, 05:25 AM
  2. need help with extern pointers.
    By broli86 in forum C Programming
    Replies: 17
    Last Post: 04-11-2008, 10:16 AM
  3. API "Clean Up" Functions & delete Pointers :: Winsock
    By kuphryn in forum Windows Programming
    Replies: 2
    Last Post: 05-10-2002, 07:53 PM
  4. pointers, functions, parameters
    By sballew in forum C Programming
    Replies: 3
    Last Post: 11-11-2001, 10:33 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21