简体   繁体   English

用strlen函数声明数组的长度

[英]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 我正在制作一个程序来打印您的姓名首字母(例如,名称:Ben vdr Output:BVDR),并且在处理此数组时遇到了麻烦

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(); initials.c:8:21:错误:使用未声明的标识符's'字符串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) VLA不是有效的C ++ (糟糕,您使用的是C)
  • Either you are eclipsing some other s with a new s variable, or 您是用新的s变量遮盖了其他 s ,还是
  • You are trying to use s before it is properly scoped (must be after the equal sign) 您正在尝试先使用s然后再对其进行适当范围划分(必须等号之后
  • Arrays are zero-indexed, so assigning to element 100 of a 100-element array is a fencepost error. 数组的索引为零,因此将100个元素的数组的元素100分配给篱笆墙错误。
  • strlen() works over C-strings, not std::string . strlen()适用于C字符串,而不适用于std::string (ditto) (同上)

As mentioned by MM , if you are only getting a single string, do just that: 正如MM提到的,如果你只得到一个字符串,做到这一点:

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()调用

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. 如果要为c-string中s每个字符创建一个字符串数组,则必须分多个步骤进行。

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. 通常,输入未知长度字符串的方法是在get_string函数内部使用动态分配。 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. 在声明s之前(或之前),无法获得s的长度。 You probably want to do something like: 您可能想要执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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