所以我正在编写一个程序,将用户定义数量的数组存储到用户定义大小的数组中,目前我正在尝试打印出输入的每个字符串,但不知道如何将以前的字符串存储到其他地方。例如,如果用户想要 4 个字符串,我只能打印出最后一个。 我的第一个想法是为字符串创建另一个数组,当我将用户输入的字符串放入其中时该数组会增长,但我不知道如何实现这一点并将字符串分隔成更大的字符串。 我如何在末尾重复 printf 语句,以便它打印出所有输入的字符串,而不仅仅是最后一个? 如何为给定的字符串创建空间,而不是覆盖它们? 在输入下一个字符串之前,如何将字符串发送到内存中的其他位置,以及如何访问它? 这是到目前为止的代码 (进行中)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char *argv[]){
int i, length, amt;
char *ptr, *thetotalstring;
i=0;
printf("enter string amount: ");
scanf("%d",&amt);
for(;i<amt;i++){
printf("Enter the length of the string: ");
scanf("%d", &length); //length is defined
ptr = malloc(length/2*sizeof(char)); //allocate the space
printf("Please enter string %d: ", (i+1));
scanf("%s", ptr); //get the string
thetotalstring = realloc(ptr, amt*length*sizeof(char));
}
//allocate more
//space in a bigger string to hold other strings??
for(i=0;i<amt;i++){
printf("%s", thetotalstring);
}
return 0;
}
最佳答案
可以使用指针吗?
int *arrop[3];
例子
int *arrop[3];
int a = 10, b = 20, c = 50, i;
arrop[0] = &a;
arrop[1] = &b;
arrop[2] = &c;
for(i = 0; i < 3; i++)
{
printf("Current = %d\t Value = %d\n", arrop[i], *arrop[i]);
}
关于c - 如何为多个数组动态分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53642787/