Thread: passing a string to a function from main

  1. #1
    Registered User
    Join Date
    May 2012

    passing a string to a function from main

    i would like to know if i need to dinamically allocate a string in main before passing it to a function that i have created.
    in that function i just read the string and do not change any chat in it.

    thank you in advance for the answer

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    No, you can pass a pointer to the first element of a fixed size array declared in the main function. What you do need is to be careful to also specify the size of the array so that the string read into that array will not exceed the boundaries of 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
    Jun 2005
    Given the lack of clarity of your question, the answer is "it depends".

    The caller of a function is always responsible for passing information the function needs, in the form it expects. Dynamic memory allocation might be necessary to achieve that or it might not - although your function would have no way of detecting whether a passed string was allocated dynamically or not. It depends on what your function actually does - and you have supplied no useful information whatsoever about that.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing variable from an outside function to main?
    By ZeroDivision in forum C Programming
    Replies: 6
    Last Post: 11-08-2013, 08:32 PM
  2. Passing variable from function - main - function
    By ulti-killer in forum C Programming
    Replies: 2
    Last Post: 11-01-2012, 12:14 PM
  3. Passing array back to main function
    By greg677 in forum C Programming
    Replies: 11
    Last Post: 05-01-2010, 04:27 PM
  4. passing variables from main to another function
    By bazzano in forum C Programming
    Replies: 2
    Last Post: 03-06-2006, 07:30 PM
  5. Passing a double array from main to another function
    By Loctan in forum C++ Programming
    Replies: 2
    Last Post: 01-04-2005, 05:19 PM

Tags for this Thread