passing a string to a function from main

This is a discussion on passing a string to a function from main within the C Programming forums, part of the General Programming Boards category; hi, i would like to know if i need to dinamically allocate a string in main before passing it to ...

  1. #1
    Registered User
    Join Date
    May 2012
    Posts
    34

    passing a string to a function from main

    hi,
    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
    Location
    Singapore
    Posts
    22,308
    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.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,677
    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, Sunshine, 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, 01:14 PM
  3. Passing array back to main function
    By greg677 in forum C Programming
    Replies: 11
    Last Post: 05-01-2010, 05: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


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