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":0x605050l->corrente->str = "I Like Coffe":0x605050目前为止一切都很好。
现在状态在realloc之后(在赋值*s = tmp)之前):
*w = "":0x605050*s = "":0x605050l->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不变。
发布于 2015-05-15 03:17:42
如果我正确地理解了您,并且您希望在保持*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不变,但在s2中连接"ss2"。如果我再次误解了,请告诉我。
#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);
}输出
$ ./bin/realloc_post
a: I like coffee.
b: I like coffee.I like tea.https://stackoverflow.com/questions/30250731
复制相似问题