Clo*_*kSC 1 c string dynamic-memory-allocation
在程序开始时,我需要为未知数量的字符串(大小未知)动态分配内存,以便以后使用。要获得用户的字符串数,我需要:
int main(int argc, char *argv[]){
int number = atoi(argv[1]);
Run Code Online (Sandbox Code Playgroud)
到目前为止,一切都很好。现在,“ number”保存着用户在命令行上输入的用于执行代码的数字。现在是我不太了解的部分。现在,我需要动态存储字符串的长度以及字符串的内容。例如,我希望程序运行如下:
Enter the length of string 1: 5
Please enter string 1: hello
Enter the length of string 2: ...
Run Code Online (Sandbox Code Playgroud)
为此,我认识到必须创建一个字符串数组。但是,我不太了解指针的概念,而没有。我想要的可能是如何简化此过程?
您从一开始就知道number要存储字符串,因此需要一个大小数组number来存储指向每个字符串的指针。
您可以用来malloc为numberchar指针动态分配足够的内存:
char** strings = malloc(number * sizeof(char*));
Run Code Online (Sandbox Code Playgroud)
现在您可以循环number时间并动态分配每个字符串:
for (int i = 0; i < number; i++) {
// Get length of string
printf("Enter the length of string %d: ", i);
int length = 0;
scanf("%d", &length);
// Clear stdin for next input
int c = getchar(); while (c != '\n' && c != EOF) c = getchar();
// Allocate "length" characters and read in string
printf("Please enter string %d: ", i);
strings[i] = malloc(length * sizeof(char));
fgets(strings[i], length, stdin);
}
Run Code Online (Sandbox Code Playgroud)