How Can You Determine the Number of Strings in a C++ Static Array?

  • Thread starter Thread starter Medicol
  • Start date Start date
  • Tags Tags
    Array Memory
AI Thread Summary
To determine the number of strings in a C++ static array, one can utilize a while loop to count until a null pointer is encountered. When creating a static array of strings, it is important to define the size in advance, as indicated by the teacher's guidance. A function can be designed to return both the pointer to the array and the count of strings by using parameters for the count. Static arrays maintain their duration throughout the program's execution, allowing safe returns of pointers to static variables. Overall, understanding the structure and initialization of static arrays is crucial for effective memory management in C++.
Medicol
Messages
223
Reaction score
54
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



Homework Equations


new


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.
 
Physics news on Phys.org
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.
 
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:

Similar threads

Back
Top