typedef struct element element;
struct element{
dado_t str;
elemento* preview;
elemento* next;
};
typedef struct lista2 lista2;
struct lista2{
elemento* primeiro;
elemento* ultimo;
elemento* corrente;
};
void caller(lista2* l){
char *s = l->corrente->str;
char *s2 = l->corrente->next->str;
my_func(&s, &s2);
}
void my_func(char **s, char**s2){
size_t len = strlen(*s);
size_t len2 = strlen(*s2);
char *w = *s;
char *tmp = realloc(w, len + len2 + 1); //PROBLEM HERE
if(tmp != NULL)
*s = tmp;
else
*s = NULL;
strcat(*s, *s2);
}
当我运行我的代码时(realloc()
之前):
*w = "I Like Coffe"
:0x605050
*s = "I Like Coffe"
:0x605050
l->corrente->str = "I Like Coffe"
:0x605050
到目前为止一切顺利。
现在状态 realloc
之后(在分配*s = tmp)
:
*w = ""
:0x605050
*s = ""
:0x605050
l->corrente->str = ""
:0x605050
还好,对吗?现在我在*s = tmp
之后得到了什么:
*w = ""
:0x605050
*s = "I Like Coffe"
:0x605160
已更改l->corrente->str = ""
:0x605050
我需要什么:
1)更改l->corrente->str
中的my_func()
值;
2)或者不知何故,在strcat之后将*s
值更改为新值。并保持l->corrente->str
相同。
答案 0 :(得分:1)
如果我理解正确并且您希望在保持*s
或l->corrente->str
相同的同时创建连接值,那么让my_func
返回指向该值的指针会更有意义新的连接字符串,同时保持两个输入字符串不变。如果我不明白你的目的是什么,请发表评论。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *my_func(char *s, char*s2);
int main (void) {
char *a = strdup ("I like coffee.");
char *b = strdup ("I like tea.");
char *c = my_func (a, b);
printf ("\n a: %s\n b: %s\n c: %s\n\n", a, b, c);
return 0;
}
char *my_func(char *s, char*s2)
{
size_t len = strlen(s);
size_t len2 = strlen(s2);
char *w = strdup (s);
char *tmp = realloc(w, len + len2 + 1); //PROBLEM HERE
if(!tmp) {
fprintf (stderr, "%s() error: realloc failed.\n", __func__);
return NULL;
}
w = tmp;
strcat(w, s2);
return w;
}
<强>输出强>
$ ./bin/realloc_post
a: I like coffee.
b: I like tea.
c: I like coffee.I like tea.
*s
,在*s2
而不是返回指针,my_func
的此实现仍然是void
并且s
和s2
,s
保持不变,但是连接{{1}在"ss2"
中。如果我再次误解,请告诉我。
s2
<强>输出强>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void my_func(char **s, char **s2);
int main (void) {
char *a = strdup ("I like coffee.");
char *b = strdup ("I like tea.");
my_func (&a, &b);
printf ("\n a: %s\n b: %s\n\n", a, b);
free (a);
free (b);
return 0;
}
void my_func(char **s, char **s2)
{
size_t len = strlen(*s);
size_t len2 = strlen(*s2);
char *w = strdup (*s);
char *p = *s2; /* save start address to free */
char *tmp = realloc(w, len + len2 + 1);
if(!tmp) {
fprintf (stderr, "%s() error: realloc failed.\n", __func__);
return;
}
strcat(tmp, *s2);
*s2 = tmp;
free (p);
}