C 自动定义数组大小
C define array size automatically
我正在尝试将 const char* string
复制到 char array[?]
C 中有没有自动设置数组大小的方法? char word[255];
而不是使用 255
我的程序将在我的案例 10 中自动使用正确的大小。如果有更好的方法,我愿意接受任何建议。
const char* test_str = "my string.";
int lenght = strlen(test_str), x=0;
char word[255] = {'[=10=]'};
//memset(word, '[=10=]', sizeof(word));
while (x < lenght) {
word[x] = test_str[x];
x++;
}
printf("%s", word);
编辑:删除了 memset(word, '[=15=]', sizeof(word));
并替换为 word[255]= {'[=16=]'};
这里有两个选择。
第一个是使用 malloc
。基本上是这样使用的:
char *word = malloc(sizeof *word * (strlen(test_str)+1));
完成后,释放内存。
free(word);
另一种选择是使用 VLA(可变长度数组):
char word[strlen(test_str) + 1];
我建议使用 malloc
。有点乱,但在我看来,VLA:s有相当大的弊端,如果你要学C的话,反正迟早要学malloc
,但你可以做得很完美没有 VLA:s.
也很好
我在这里写了一个关于为什么我认为 VLA:s 不好的答案:
我正在尝试将 const char* string
复制到 char array[?]
C 中有没有自动设置数组大小的方法? char word[255];
而不是使用 255
我的程序将在我的案例 10 中自动使用正确的大小。如果有更好的方法,我愿意接受任何建议。
const char* test_str = "my string.";
int lenght = strlen(test_str), x=0;
char word[255] = {'[=10=]'};
//memset(word, '[=10=]', sizeof(word));
while (x < lenght) {
word[x] = test_str[x];
x++;
}
printf("%s", word);
编辑:删除了 memset(word, '[=15=]', sizeof(word));
并替换为 word[255]= {'[=16=]'};
这里有两个选择。
第一个是使用 malloc
。基本上是这样使用的:
char *word = malloc(sizeof *word * (strlen(test_str)+1));
完成后,释放内存。
free(word);
另一种选择是使用 VLA(可变长度数组):
char word[strlen(test_str) + 1];
我建议使用 malloc
。有点乱,但在我看来,VLA:s有相当大的弊端,如果你要学C的话,反正迟早要学malloc
,但你可以做得很完美没有 VLA:s.
我在这里写了一个关于为什么我认为 VLA:s 不好的答案: