Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Dale Cooper

macrumors regular
Original poster
Sep 20, 2005
218
0
I'm having a hard time passing chars around in C. Can anyone advice me on what to replace ??? with for this to work, or have a better way to do this? Thanks!
Code:
[...]
        char ??? listOfVowels= makeVowels();
}

char ??? makeVowels() {
	char (???) vowels[8];
        vowels[0] = 'a';
        vowels[1] = 'e';
        vowels[2] = 'i';
        vowels[3] = 'o';
        vowels[4] = 'u';
	return vowels;
}
 

Guiyon

macrumors 6502a
Mar 19, 2008
771
4
Cambridge, MA
You can't return the array from inside makeVowels because it is allocated on the stack. The moment you bounce back up it's gone. There are several ways you can go about writing this sort of function though, below are two of them (with comments!).

Code:
#define kVOWEL_COUNT 5

 /* Just fill in a pre-defined array.
  *   Be careful with this one! You need to
  *     make sure you always have enough
  *     space in the passed array otherwise
  *     BadThings™ will happen.
  */
void makeVowels_arg( char *vowels ) {
    vowels[0] = 'a';
    vowels[1] = 'e';
    vowels[2] = 'i';
    vowels[3] = 'o';
    vowels[4] = 'u';
}

 /*
  * Dynamically allocate a new array and
  *  return a pointer to it.
  * You will need to free() the returned value
  *  once you are done with it!
 */
char* makeVowels_alloc( void ) {
    char *vowels = (char*)malloc( sizeof( char ) * kVOWEL_COUNT );
    vowels[0] = 'a';
    vowels[1] = 'e';
    vowels[2] = 'i';
    vowels[3] = 'o';
    vowels[4] = 'u';
    return vowels;
}

int main( void ) {
    char varr[kVOWEL_COUNT] = {'\0'};
    char *vptr = NULL;
    
   /* Since the varr array exists in the current scope
    *   we can just pass a pointer to it and have this
    *   function fill it in. Remember, the array will still
    *   disappear once we leave the current scope!
    */
    makeVowels_arg( (char*)varr );
  

   /* Here we are getting a dynamically allocated array
    *   back from the makeVowels function. The difference
    *   between this function and the above one is that the
    *   array is allocated on the heap which means it will be
    *   around until either the program exits or you free()
    *   the pointer. Be careful with this one! If you don't manage your
    *   memory well you will end up with leaks.
    */
    vptr = makeVowels_alloc();
    free( vptr );
    vptr = NULL; // Not necessary but I'm paranoid.

    return 0;
}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.