简体   繁体   中英

Declaring length of an array with a strlen function

I was making a program to print your initials (ex. Name:Ben vdr Output:BVDR) and was having trouble with this array

string s[strlen(s)] = get_string();

I was getting this error

initials.c:8:21: error: use of undeclared identifier 's' string s[strlen(s)] = get_string();

How would I get this to work?

The code makes no sense.

  • VLAs are not valid C++ (oops, you're using C)
  • Either you are eclipsing some other s with a new s variable, or
  • You are trying to use s before it is properly scoped (must be after the equal sign)
  • Arrays are zero-indexed, so assigning to element 100 of a 100-element array is a fencepost error.
  • strlen() works over C-strings, not std::string . (ditto)

As mentioned by MM , if you are only getting a single string, do just that:

char* s = get_string();  // get_string() malloc()s a proper char array
...
free( s );

If you wish to declare an array of strings, do so and initialize the array properly:

const unsigned N = 100;
char* s[ N ] = { get_string(), "" };  // first elt is copy, all others are empties

or

char* s[ N ] = { get_string() };  // N copies of result

Again, don't forget to free() exactly that string, exactly once:

free( s[0] );

If you wish to create an array of strings for every character in the c-string s , you'll have to do that in multiple steps.

char* p = get_string();
char* ss[ strlen( p ) ] = { NULL };  // VLA
...
free( p );

or

char* p = get_string();
char** ss = malloc( strlen( p ) * sizeof( char* ) );  // dynamic
...
free( ss );
free( p );

The length of an array must be known at the point of declaring it. Also, arrays cannot be returned from functions.

Normally the way to input a string of unknown length is to use dynamic allocation inside the get_string function. Then the function returns a pointer to the first character of the dynamically allocated block.

The calling code looks like:

char *s = get_string();
// ... use s ...
free(s);   // release the dynamically allocated block

You can't get the length of s before (or as) it is being declared. You probably want to do something like:

string tmp = get_string();
string s[strlen(tmp)] = tmp; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM