pointers and arrays

This is a discussion on pointers and arrays within the C++ Programming forums, part of the General Programming Boards category; hey i am trying to learn pointers and references. how can i pass an array of characters by reference to ...

  1. #1
    Registered User
    Join Date
    Apr 2006
    Posts
    9

    pointers and arrays

    hey i am trying to learn pointers and references.

    how can i pass an array of characters by reference to a function?

    Code:
    void funct(char *text)
    {
    	cout << *text << endl;
    	*text = 'c';
    }
    
    int main()
    {
    	char text;
    	cin >> text;
    	funct(&text);
    	cout << text << endl;
    	return 0;
    }
    this works with one character but i can't figure out how to make it work with an array

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,318
    Arrays are automatically passed by reference. If you want to pass a null-terminated character array, you can make the function parameter char* text or char text[] since the size is determined by the terminating null character. For other arrays, you have to pass the size as a separate parameter, or as part of the array parameter: int arr[5].

    Of course, in C++ you should just use the C++ string class instead null-terminated character arrays, and vector (or some other container) instead of regular arrays.

  3. #3
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,705
    You wouldn't need to pass an array by reference. You already pass the array by pointer. Just use cin.get(), fill a character array, and pass that to funct. What happens after that will be dependant on what you're trying to do. You'd have to use a loop to fill the array with 'c'. Or use memset().

  4. #4
    Registered User
    Join Date
    Apr 2006
    Posts
    9
    that was simple lol

    thanks daved

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointers & arrays and realloc!
    By zesty in forum C Programming
    Replies: 14
    Last Post: 01-19-2008, 03:24 PM
  2. Pointers and multi dimensional arrays
    By andrea72 in forum C++ Programming
    Replies: 5
    Last Post: 01-23-2007, 03:49 PM
  3. Passing pointers to arrays of char arrays
    By bobthebullet990 in forum C Programming
    Replies: 5
    Last Post: 03-31-2006, 04:31 AM
  4. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 08:32 AM
  5. Help understanding arrays and pointers
    By James00 in forum C Programming
    Replies: 2
    Last Post: 05-27-2003, 01:41 AM

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