我正在创建一个简单的程序(下面的代码),它询问用户他/她的名字,并向你打招呼。我只是想知道我在代码中所做的注释是否正确。我试图了解数组是如何创建的,以及我们如何为它们分配空间并处理它们,这样我们就不会超出内存范围。
#include <stdio.h>
// "-" (no quotes, just the dash) means garbage values
int main() {
char name[5];
// name = [0] [1] [2] [3] [4] [5]
// - - - - - -
char fav_nums[5];
// fav_nums = [0] [1] [2] [3] [4] [5]
// - - - - - -
printf("What is your name (max characters 5)?\n");
scanf("%s\n", name);
// I typed "Sammy" (no quotes)
// name = [0] [1] [2] [3] [4] [5]
// S a m m y \0
printf("Hi, %s\n", name);
printf("Enter your 5 favorite numbers!\n");
int i = 0;
while (i < 5) {
scanf("%d", fav_nums[i]);
i++;
}
// I typed 2 3 6 7 1
// fav_nums = [0] [1] [2] [3] [4] [5]
// 2 3 6 7 1 -
fav_nums[5] = '\0';
// fav_nums = [0] [1] [2] [3] [4] [5]
// 2 3 6 7 1 \0
printf("Cool, I love");
i = 0;
while (i < 5) {
printf(" %d", fav_num[i]);
i++;
}
printf("\n");
return 0;
}
最佳答案
除了@chux的回答之外,如果你想读取任意长度的行:
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char *name = NULL;
size_t length = 0;
size_t size = 0;
size_t const buffer_growth = 10; // +10 ... or whatever length you expect
int ch;
while ((ch = getchar()) != EOF && ch != '\n' && ch != '\r')
{
if (length + 1 >= size) {
if(size + buffer_growth <= size) // we reached or overflow the max
break; // object size on the platform
char *new_name = realloc(name, size += buffer_growth);
if (!new_name) {
free(name);
fputs("Memory allocation failed :(\n\n", stderr);
return EXIT_FAILURE;
}
name = new_name;
}
name[length++] = ch;
name[length] = '\0';
}
printf("\"%s\"\n", name);
}
关于c - 我如何知道要为数组分配多少空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53236107/