1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Creating memory for array

  1. Sep 10, 2014 #1
    1. Using new to create a memory block for a static array of strings. How to know the number of strings in an array of strings



    2. Relevant equations
    new


    3. The attempt at a solution

    1. static char ** array=new char*[]; // why the empty [] ? Will I get a minus point if coding like this ? My teacher says subscript data should be known in advance
    .
    2. If I have a library function that has the signature
    PHP:
    char** doSomething(...);
    I am using it like this

    PHP:
    char**ret=doSomething();
    I then would like to know the number of strings returned from that function.
    I am taking the first course in IT programming, I chose C++ language.
     
  2. jcsd
  3. Sep 11, 2014 #2

    jedishrfu

    Staff: Mentor

    I think you have to count them until the pointer is a null.

    You could use a while loop and increment a counter while the ret pointer != NULL.
     
  4. Sep 11, 2014 #3

    rcgldr

    User Avatar
    Homework Helper

    Since the problem statement mentions "static" array of strings, then I assume it's a fixed number of strings, and that's it's an array of pointers to the first characters of a set of strings. The function could include a parameter that would be a pointer or a reference to a string count that the function sets. There could also be a parameter to return the pointer to the array, or it could be a return value. Note that a static variable's name scope is local, but it's duration is for the entire time a program (thread) is running, so it should be safe to return a pointer to a static variable in a function. Since these are static arrays, there's no need for new (I chose as to represent array of strings):

    static char * as[4] = {"one", "two", "three", "four"};

    optionally if using a null pointer to indicate the end of an array:

    static char * as[5] = {"one", "two", "three", "four", (char *)0};

    or an array with all null pointers:

    static char * as[5];
     
    Last edited: Sep 11, 2014
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: Creating memory for array
  1. Memory module (Replies: 2)

Loading...