I need an array of strings. The length of a string is known at compile-time and it is crucial that each string takes up this much space. The number of strings on the other hand is only known at runtime. What is the syntax for this?
我需要一个字符串数组。字符串的长度在编译时是已知的,并且每个字符串占用这么多空间是至关重要的。另一方面,字符串的数量仅在运行时已知。这是什么语法?
char* data[STRLENGTH]
is incorrect syntax. char** data
mostly works but then sizeof(data[0])
is wrong -- it should be equal to STRLENGTH
.
char * data [STRLENGTH]语法不正确。 char **数据主要起作用但是sizeof(data [0])是错误的 - 它应该等于STRLENGTH。
3 个解决方案
#1
10
@Daniel is correct, but this code can confuse people who read it - it's not something you usually do. To make it more understandable, I suggest you do it in two steps:
@Daniel是正确的,但是这段代码可能会让阅读它的人感到困惑 - 这不是你通常做的事情。为了使其更容易理解,我建议您分两步完成:
typedef char fixed_string[STRLENGTH];
fixed_string *data;
#2
6
char* data[STRLENGTH]
declares an array of STRLENTGH
pointers to char
. To declare a pointer to array of STRLENGTH
char
s, use
声明一个指向char的STRLENTGH指针数组。要声明指向STRLENGTH字符数组的指针,请使用
char (*data)[STRLENGTH]
#3
5
char (*data)[LEN]; // where LEN is known at compile time
...
data = malloc(sizeof *data * rows); // where rows is determined at run time
...
strcpy(data[i], some_name);
...
printf("name = %s\n", data[i]);
...
free(data);
Note that data
is a pointer type, not an array type (data
is a pointer to a LEN
-element array of char
). The malloc
call will dynamically allocate enough memory to hold rows
arrays of length LEN
. Each data[i]
will be type char [LEN]
.
请注意,数据是指针类型,而不是数组类型(数据是指向char的LEN元素数组的指针)。 malloc调用将动态分配足够的内存来保存长度为LEN的行数组。每个数据[i]将是char [LEN]类型。
#1
10
@Daniel is correct, but this code can confuse people who read it - it's not something you usually do. To make it more understandable, I suggest you do it in two steps:
@Daniel是正确的,但是这段代码可能会让阅读它的人感到困惑 - 这不是你通常做的事情。为了使其更容易理解,我建议您分两步完成:
typedef char fixed_string[STRLENGTH];
fixed_string *data;
#2
6
char* data[STRLENGTH]
declares an array of STRLENTGH
pointers to char
. To declare a pointer to array of STRLENGTH
char
s, use
声明一个指向char的STRLENTGH指针数组。要声明指向STRLENGTH字符数组的指针,请使用
char (*data)[STRLENGTH]
#3
5
char (*data)[LEN]; // where LEN is known at compile time
...
data = malloc(sizeof *data * rows); // where rows is determined at run time
...
strcpy(data[i], some_name);
...
printf("name = %s\n", data[i]);
...
free(data);
Note that data
is a pointer type, not an array type (data
is a pointer to a LEN
-element array of char
). The malloc
call will dynamically allocate enough memory to hold rows
arrays of length LEN
. Each data[i]
will be type char [LEN]
.
请注意,数据是指针类型,而不是数组类型(数据是指向char的LEN元素数组的指针)。 malloc调用将动态分配足够的内存来保存长度为LEN的行数组。每个数据[i]将是char [LEN]类型。