我处于一种两难的境地,因此,首先我想道歉,如果下一个问题会更不雅观,或者之前曾询问过(我无法找到那些答案虽然)。免费动态分配阵列C
无论如何,我会以一个任务为例来解释它(这不是作业,它只是为了我的问题)。这里有云:
Given a string from stdin index each word, then print each word on one line.
Example:
str[] = "Stack is awesome"
str_index {
[0] => "Stack"
[1] => "is"
[2] => "awesome"
}
我知道,有很多方法可以解决这个问题,但同样,我的问题
裸这种解决方案的缘故:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/* fgets adds an unwanted '\n' at the end, so I made
* a special function to read from stdin that removes
* that '\n'.
*/
int read(char *str, int size) {
// fgets adds an unwanted '\n' at the end, so we remove it
fgets(str, size, stdin);
int length = strlen(str);
str[length - 1] = '\0';
return length;
}
/* A function that breaks a string into words, indexes them
* and prints them out, all done dynamically with malloc.
*/
void str_index(char *str) {
char **index, *ptr;
int i = 0, number_of_words;
index = malloc(sizeof(char *));
ptr = strtok(str, " ");
for(i = 0; ptr != NULL; i++) {
index = realloc(index, (i + 1) * sizeof(char *));
index[i] = malloc(50 * sizeof(char));
strcpy(index[i], ptr);
ptr = strtok(NULL, " ");
}
number_of_words = i;
for(i = 0; i < number_of_words; i++) {
printf("%s\n", index[i]);
}
return;
}
int main() {
char str[250];
read(str, 250);
str_index(str);
return 0;
}
问题
- 我在哪里必须释放我在str_index中动态分配的数组?
- 我们是否必须在函数str_index中释放它们?如果是这样,为什么? 我所知道的是,当一个函数完成时,所有本地的 变量都被销毁。
- 为什么我们必须将它们释放出来?并不是主要功能,因此在完成执行后,该功能中定义的所有变量都将被销毁。
你是什么意思,按程序要求? –
如果您从函数返回指针,则不应该在该函数中释放此指针。你应该在'main'中释放这个指针。如果函数没有返回指针,那么它应该在该函数中被释放。 – haccks