c - Using Realloc to resize a char ** -
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); }
when run code(before realloc()
):
*w = "i coffe"
memory adress:0x605050
*s = "i coffe"
memory adress:0x605050
l->corrente->str = "i coffe"
memory adress:0x605050
all far.
status after realloc
(before assign *s = tmp)
:
*w = ""
memory adress:0x605050
*s = ""
memory adress:0x605050
l->corrente->str = ""
memory adress:0x605050
still ok, right ? after *s = tmp
:
*w = ""
memory adress:0x605050
*s = "i coffe"
memory adress:0x605160
changedl->corrente->str = ""
memory adress:0x605050
what need:
1) change l->corrente->str
value in my_func()
;
2) or somehow, change *s
value new value after strcat. , keep l->corrente->str
same.
if understand correctly , want create concatenated value while keeping *s
or l->corrente->str
same, make more sense have my_func
return pointer new concatenated string while keeping both input strings unchanged. if don't understand attempting do, please leave comment.
#include <stdio.h> #include <stdlib.h> #include <string.h> char *my_func(char *s, char*s2); int main (void) { char *a = strdup ("i coffee."); char *b = strdup ("i 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; }
output
$ ./bin/realloc_post a: coffee. b: tea. c: coffee.i tea.
void - preserving *s
, concatenate in *s2
instead of returning pointer, implementation of my_func
remains void
, takes s
, s2
, keeping s
unchanged, concatenating "ss2"
in s2
. if misunderstood again, let me know.
#include <stdio.h> #include <stdlib.h> #include <string.h> void my_func(char **s, char **s2); int main (void) { char *a = strdup ("i coffee."); char *b = strdup ("i 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 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); }
output
$ ./bin/realloc_post a: coffee. b: coffee.i tea.
Comments
Post a Comment