Thread: Functions+Arrays+pointers

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    82

    Functions+Arrays+pointers

    Good evening all.

    Wanted some advice/help on functions/arrays/pointers and there relationship.

    Below is the practice code i've been writing trying to get certain elements to work.

    I originally wanted to to have a function that gets user input and anotehr function that can change this user input. apparently even if you declare a variable an array in one function you can't copy/change it's contents with out pointers.

    ie no....

    function1();

    {
    int ArrayName[100]
    }

    and then

    function2(int theArrayName)

    {
    // alter ArrayName some how
    }

    Functions only take first element of array or so i was told.

    So anyway i began the quest of learning Pointers so i could get at those arrays and edit them in other functions.

    code:

    Code:
    #include <iostream>
    #include <stdio.h>
    using namespace std;
    
    
    int Function1()
    
    {
      
    int *pointer[5]; //declare pointer to int[arry]
    int Input[5] ; //declare normal int[arry]
    
    pointer[5] = &Input[5]; //assign address of Input to pointer
    
    
     cout << "Enter Input" << endl;
     cin >> *pointer[5]; // input value to address pointed to by pointer
     cout << *pointer[5] << endl;
     
    cin.get();
    return *pointer[5];
    
    }
    
    
    /*int Function2(int *pointer[5])
    
    {
        
    cout << *pointer[5] << endl:
        
    
    cin.get();
    
    }
    
    */
    int main ()
    
    {
        Function1();
        
    
        //Function2(*pointer[5]);
        
        
        cin.get();
    }
    Now above is just a one to one, nearly of the pointers tutorial what i need some advice on is creating my second function which is "//" out, that can take what is passed into Input[5] and allow me to edit, change and do funky stuff to it.

    One other thing is creating a Char[arry], apparently:

    Char ArryName[100];

    isn't an array with 100 elements but a variable nameed ArryName containing 100 single element strings? is that so?

    Is Char Str[100] correct?

    Anyway moving on, all help is appreciated and considering how hot it is at night these days i might aswell continue into the early morning

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I originally wanted to to have a function that gets user input and anotehr function that can change this user input. apparently even if you declare a variable an array in one function you can't copy/change it's contents with out pointers.
    In this case, you may find it better to pass an existing array to the function. The way you are doing it means that the array is local to the function, so it doesnt exist outside of the function.

    Functions only take first element of array or so i was told.
    I think you misunderstood what you were told. When an array is passed to a function, it decays to a pointer to its first element. You can still access the rest of the array through the pointer, but things such as sizeof(arrayname) will return the size of the pointer, not the array.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Oct 2005
    Posts
    82
    well did some changes and i think i got the pointer to work in the second function.

    Changed it to char:

    Code:
    #include <iostream>
    #include <stdio.h>
    using namespace std;
    
    
    char* GetFunction1()
    
    {
      
    char *pointer; //declare pointer to int[arry]
    char Input[5] ; //declare normal int[arry]
    
    pointer = &Input[5]; //assign address of Input to pointer
    
    
     cout << "Enter Input" << endl;
     cin >> *pointer; // input value to address pointed to by pointer
     cout << *pointer << endl;
     cout << "worked" << endl;
    cin.get();
    
    return pointer;
    
    }
    
    
    char GetFunction2(char *pointer)
    
    {
        char func2;
        
        func2 = *pointer;
        
    cout << func2 << endl;
    cout << "Second Function" << endl;    
    
    cin.get();
    }
    
    
    int main ()
    
    {
       char *pointer = GetFunction1();
       
        GetFunction2(pointer);
        
        cin.get();
    }
    Still doesn't return everything in the array though as you mentioned above it wouldn't, read on one topic i may need to use some kind of for loop, anyone know what it could be or how?

  4. #4
    Registered User
    Join Date
    Oct 2005
    Posts
    82
    Chnaged my second function to include a For Loop to cout what is in each element of the array pointed to by the pointer.

    However it just prints out gibberish, which i think means that it isn't getting what it wants from the pointer or func2[5] array is just ating local and returning whats in it when called which is nothing yet.

    here are the changes:

    Code:
    char GetFunction2(char *pointer)
    
    {
        char func2[5];
        func2[5] = *pointer;
       
      for (char i = 0; i < 5; ++i)
        
      {  
        
       cout << func2[i] << endl;
       cout << "Second Function" << endl;    
    
        cin.get();
      }
    
    }

  5. #5
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Code:
    #include <iostream>
    #include <stdio.h>
    using namespace std;
    
    char* GetFunction1()
    {
        char *pointer; //declare pointer to int[arry]
        char Input[5] ; //declare normal int[arry]
    
        pointer = &Input[5]; //assign address of Input to pointer
    You are assigning the address of the 6th element of the array Input to the pointer. This is past the end of the array and an invalid index and therefore pointer is now invalid (points to nothing usefull).


    Code:
        cout << "Enter Input" << endl;
        cin >> *pointer; // input value to address pointed to by pointer
    You are dereferencing the invalid pointer and this is simply the wrong way to accept user input using a pointer. You shouldn't dereference the pointer.


    Code:
        cout << *pointer << endl;
        cout << "worked" << endl;
        cin.get();
    
        return pointer;
    }
    You are trying to (had it been pointing to a valid address to begin with) return the address of a local (local to the function it is declared in) variable. When the function exits, this local array is popped off the stack and therefore even if pointer had been assigned correctly in the first place, it would still be pointing to an invalid address.


    Code:
    char GetFunction2(char *pointer)
    {
        char func2;
        
        func2 = *pointer;
        
        cout << func2 << endl;
        cout << "Second Function" << endl;    
    
        cin.get();
    }
    
    
    int main ()
    {
        char *pointer = GetFunction1();
       
        GetFunction2(pointer);
        
        cin.get();
    }
    There are several things you can do:

    1) You can declare an array in your main function and pass it into both of your functions as a parameter which in turn will populate said array and then display the contents.

    2) You could declare the array in GetFunction1 as static which mean the memory will not be popped off the stack once the function exits. This is not a recommended approach.

    3) You can stop using pointers and arrays and such. This is the C++ forum, learn to use a string container instead.

    [edit]
    4) You can dynamically allocate space in the GetFunction1 function and return a pointer to that memory.
    [/edit]
    Last edited by hk_mp5kpdw; 07-05-2006 at 01:06 PM.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  6. #6
    Registered User
    Join Date
    Oct 2005
    Posts
    82
    Thank you, i corrected the dereferencing and input. And made the arrays Static. I only doddled with pointers because someone suggested to use it.

    I'll try and right the whole thing up again using Strings like you suggested.

    Regards Wolfe

  7. #7
    Registered User
    Join Date
    Oct 2005
    Posts
    82
    Well here it is converted to use strings, at least i think it is, it compiles and saves and prints out the input, though the second function doesn't want to print out past the second element of the array.

    Code:
    #include <iostream>
    #include <stdio.h>
    #include <cstring>
    
    using namespace std;
    
    
    string* GetFunction1()
    
    {
      
    string *pointer; //declare pointer to int[arry]
    string Input; //declare normal int[arry]
    
    pointer = &Input; //assign address of Input to pointer
    
    
     cout << "Enter Input" << endl;
     cin >> Input; // input value to address pointed to by pointer
     cout << Input << endl;
     cout << "worked" << endl;
    cin.get();
    
    pointer = &Input;
    return pointer;
    
    }
    
    
    char GetFunction2(string *pointer)
    
    {
        
        int index;
        string func2;
        func2 = *pointer;
        string total ;
       
      for (int index = 0; index < 50; ++index)
        
      {  
        
       cout << func2[index] << endl;
       cout << "Second Function" << endl;    
       total += func2[index];
       cout << "Test" << total << endl;
       
       cin.get();
      }
    
    }
    
    
    int main ()
    
    {
       string *pointer = GetFunction1();
       
        GetFunction2(pointer);
        
        cin.get();
    }
    Anyone know how to get it to print out each new element after each loop.

    ie: Input ABCDEF

    Second Function
    Test A
    ....
    Test AB

    .....
    Test ABC etc

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Well here it is converted to use strings, at least i think it is, it compiles and saves and prints out the input, though the second function doesn't want to print out past the second element of the array.
    Your GetFunction1() function still returns a pointer to a local variable. What are you trying to do?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Registered User
    Join Date
    Oct 2005
    Posts
    82
    Errr, create user input in one function, put it into an Array(originally) and then call this array and its contents in another function.

    Obviously some changes have been made along the way, getting rid of the array and using Strings.

    Is there anything wrong with returning the pointer and calling to it in the second function?

  10. #10
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Objects, such as strings, have constructors and destructors. The string's constructor is called to build/initialize the object and the destructor is called to free up any resources used by that object when said object goes out of scope. Once the function ends and the string Input is popped off the stack, the string's destructor is called. However, you are returning a pointer to that destructed object, an object that no longer exists.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  11. #11
    Registered User
    Join Date
    Oct 2005
    Posts
    82
    Quote Originally Posted by hk_mp5kpdw
    Objects, such as strings, have constructors and destructors. The string's constructor is called to build/initialize the object and the destructor is called to free up any resources used by that object when said object goes out of scope. Once the function ends and the string Input is popped off the stack, the string's destructor is called. However, you are returning a pointer to that destructed object, an object that no longer exists.

    Ahhhh, so is it possible to keep it in the "stack",

    Just tried making both the pointer and Input "STATIC", it worked in the sense that it now doesn't go away and i can access the whole string.

    But i was told abve STATIC=Bad, is there another way preferably a simple one that gives the same effect?

    Thanks

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I think you should use a std::vector<std::string>. If you do want to use a pointer to std::string, then you should use dynamic memory allocation.

    A primitive example would be:
    Code:
    #include <iostream>
    #include <string>
    
    using std::string;
    using std::cout;
    using std::endl;
    using std::cin;
    
    void readInput(string*& input, unsigned int& size)
    {
    	cout << "Enter number of strings to input: ";
    	cin >> size;
    	input = new string[size];
    	cout << "Enter input: " << endl;
    	for (unsigned int i = 0; i < size; ++i)
    	{
    		cin >> input[i];
    	}
    	cout << "worked" << endl;
    	cin.get();
    }
    
    void printInput(string* input, unsigned int size)
    {
    	for (unsigned int i = 0; i < size; ++i)
    	{
    		cout << input[i] << "\n";
    	}
    }
    
    int main()
    {
    	string* input;
    	unsigned int size;
    	readInput(input, size);
    	printInput(strings, size);
    	delete[] input;
    }
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Registered User
    Join Date
    Oct 2005
    Posts
    82
    For some reason it doesn't compile, prb with

    printInput(strings, size);

    (syntax error before ; )

    Anyway lots of questions

    You declared both Input and Size in Main and i guess call this in each function by placing them as arguments/parameters?

    ie: void readInput(string*& input, unsigned int& size)

    I assume this is better then what i did by just declaring Input as a local variable and pointing to it using pointer then returning pointer and then calling it in my other function, assuming that is what i actually did .

    When readinput function is called does Input etc get updated in main to match what is put in it? i assume so as printoutput would make no sense.

    Oh and in the function header, what does String* &input mean.
    Does it create a string and assign the address of input to it?
    why use * infront of string?

    Sorry for so many questions, i'am going to rewrite it again now.

    Regards Wolfe

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    For some reason it doesn't compile, prb with

    printInput(strings, size);

    (syntax error before ; )
    Yes, change strings to input.

    When readinput function is called does Input etc get updated in main to match what is put in it? i assume so as printoutput would make no sense.
    input and size are both passed by reference. This means that they are an alias, another name, for the input and size in main().

    Oh and in the function header, what does String* &input mean.
    Does it create a string and assign the address of input to it?
    why use * infront of string?
    string* means "pointer to string". The ampersand (&) means "pass by reference", in this context. This is different from the "address of" operator, even though it is also an ampersand.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    what does String* &input mean
    input is a reference to a pointer to string.

    I really suggest you do some reading around these and other tutorials, Cdrwolfe.
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing pointers to arrays of char arrays
    By bobthebullet990 in forum C Programming
    Replies: 5
    Last Post: 03-31-2006, 05:31 AM
  2. Problem with arrays, pointers and functions when combined
    By The Wazaa in forum C++ Programming
    Replies: 2
    Last Post: 02-05-2006, 10:44 AM
  3. Arrays and Functions
    By KunoNoOni in forum Game Programming
    Replies: 12
    Last Post: 10-04-2005, 09:41 PM
  4. Help with arrays and pointers please...
    By crazyeyesz28 in forum C++ Programming
    Replies: 8
    Last Post: 03-17-2005, 01:48 PM
  5. pointers, functions, parameters
    By sballew in forum C Programming
    Replies: 3
    Last Post: 11-11-2001, 10:33 PM