[英]Using char ** in function, that we could malloc memory for char * that is passed to her
[英]Char* created using malloc in function, compiler says address is on the stack and cannot be returned
我正在编写一个函数,该函数应该将字符串作为输入并在单词周围添加引号,然后将指针返回到新修改的字符串。
//add quotes around a single word
char** _add_quotes(char* word){
int char_count = 0;
while(word[char_count] != '\0'){
char_count++;
}
char* word_quotes = malloc((char_count+3) * sizeof(*word_quotes));
word_quotes[0] = '\"';
for(int i =0; i < char_count; i++){
word_quotes[i+1] = word[i];
}
word_quotes[char_count+1] = '\"';
word_quotes[char_count + 2] = '\0';
return (&word_quotes);
}
这是它返回的地方
char** new_word_w_qs = _add_quotes(new_word); //add quotes
//copy new word with quotes to the final string
for (int m = 0; m < word_len; m++){
new_string[string_index] = *new_word_w_qs[m];
string_index++;
}
我希望它返回堆上的字符串的地址,而不是我得到一个错误。 警告:返回与本地变量'word_quotes'关联的堆栈内存的地址[-Wreturn-stack-address] return(&word_quotes); ^ ~~~~~~~~~~
char f() {
char a = 'a';
return &a;
}
变量a
在函数返回后停止存在。 因此在函数返回后,变量a
不存在,函数返回后变量&a
的地址无效,函数返回后没有内存。
char **f2() {
char *b = "abc";
return &b;
}
这是一样的。 函数后面不存在b
变量,因此函数返回后b
变量的地址无效。 不管它是否是一个指针。 存储在b
变量中的地址仍然有效,但函数返回后变量b
的地址无效。
只需按值返回指针,而不是指针指针。
//add quotes around a single word
char* _add_quotes(char* word){
...
char* word_quotes = malloc((char_count+3) * sizeof(*word_quotes));
...
// this is the value as returned by malloc()
// the pointer value returned by malloc still valid after the function returns
return word_quotes;
}
并且可以重写您的函数以使用标准库函数:
char* _add_quotes(char* word){
char* word_quotes = calloc((strlen(word) + 3), sizeof(*word_quotes));
if (word_quotes == NULL) return NULL;
strcat(word_quotes, "\"");
strcat(word_quotes, word);
strcat(word_quotes, "\"");
return word_quotes;
}
甚至:
char* _add_quotes(char* word){
char* word_quotes = calloc((strlen(word) + 3), sizeof(*word_quotes));
if (word_quotes == NULL) return NULL;
sprintf(word_quotes, "\"%s\"", word);
return word_quotes;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.