问题
I'm a noob so don't be hard on be.
Instead of something like this;
char string[NUM OF STRINGS][NUM OF LETTERS];
Is it possible to dynamically allocate how many strings will be in the array with malloc just like when you dynamically allocate memory for char pointer? Something like this:
int lines;
scanf("%d", &lines);
char *string[NUM OF LETTERS]
string = malloc(sizeof(char) * lines);
I tried it but it doesn't work; There must be something I'm doing wrong. The other solution I thought of was:
int lines;
scanf("%d", &lines);
char string[lines][NUM OF LETTERS];
but I want to know if that's possible using malloc.
回答1:
You can also use malloc for each word, like this
char **array;
int lines;
int i;
while (scanf("%d", &lines) != 1);
array = malloc(lines * sizeof(char *));
if (array != NULL)
{
for (i = 0 ; i < lines ; ++i)
{
int numberOfLetters;
while (scanf("%d", &numberOfLetters) != 1);
array[i] = malloc(numberOfLetters);
}
}
where numberOfStrings and lengthOfStrings[i] are integers that represent the number of strings you want the array to contain, an the length of the ith string in the array respectively.
回答2:
You have two methods to implement this.
First is more complicated, cause it requires the allocation of memory for array of pointers to strings, and also allocation of memory for each string.
You can allocate the memory for entire array:
char (*array)[NUM_OF_LETTERS]; // Pointer to char's array with size NUM_OF_LETTERS
scanf("%d", &lines);
array = malloc(lines * NUM_OF_LETTERS);
. . .
array[0] = "First string\n";
array[1] = "Second string\n";
// And so on;
A disadvantage of the second method is that NUM_OF_LETTERS bytes are allocated for each string. So if you has many short strings, the first method would be better for you.
回答3:
In case you want contiguous memory allocation:
char **string = malloc(nlines * sizeof(char *));
string[0] = malloc(nlines * nletters);
for(i = 1; i < nlines; i++)
string[i] = string[0] + i * nletters;
For more detailed explanation: Read FAQ list · Question 6.16.
回答4:
int lines;
scanf("%d", &lines);
char (*string)[NUM OF LETTERS]
string = malloc(sizeof(*string) * lines);
回答5:
char **ptop;
int iStud;
int i;
printf("Enter No. of Students: ");
scanf("%d",&iStud);
ptop=(char **) malloc(sizeof(char)*iStud);
flushall();
for(i=0;i<iStud;i++)
{
ptop[i]=(char *) malloc(sizeof(char)*50);
gets(ptop[i]);
}
for(i=0;i<iStud;i++)
{
puts(ptop[i]);
}
free(ptop);
来源:https://stackoverflow.com/questions/27883242/how-to-dynamically-allocate-an-array-of-strings-in-c