如何通过引用传递struct MEMBER?我不想将整个结构传递给函数。
我试图创建一个addString函数,动态地分配足够的内存来存储结构成员中的字符串。
看起来一切正常,直到函数addString完成后我想要打印结构的title成员,其中仍然有垃圾。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct program
{
int check;
char* title;
char* channel;
};
char* addString(char* destination, char* string);
int main(void)
{
struct program* programs = (struct program*) malloc(sizeof(struct program)); //memory for the struct
addString(&(programs->title), "test"); //passes the adress of the struct member to the function
printf("%s", programs->title); //and when I print this there is still garbage in it and not the actual string "test"
return 0;
}
char* addString(char* destination, char* string)
{
*destination = (char*) malloc(strlen(string) + 1); //dynamic memory alloction for the length of the string
strcpy(destination, string); //string copy to the pointer returned from the malloc here above
return 0;
}
答案 0 :(得分:1)
red.c:17:15: warning: incompatible pointer types passing 'char **' to parameter of type 'char *'; remove & [-Wincompatible-pointer-types]
addString(&(programs->title), "test"); //passes the adress of the struct member to the function
^~~~~~~~~~~~~~~~~~
red.c:12:23: note: passing argument to parameter 'destination' here
char* addString(char* destination, char* string);
^
red.c:24:18: warning: incompatible pointer to integer conversion assigning to 'char' from 'char *'; dereference with * [-Wint-conversion]
*destination = (char*) malloc(strlen(string) + 1); //dynamic memory alloction for the length of the string
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
2 warnings generated.
值得注意的是,&(programs->title)
的类型为char **
,而非char *
。
addString()
函数可能如下所示:void addString(char** destination, char* string) {
*destination = malloc(strlen(string) + 1);
strcpy(*destination, string);
}
答案 1 :(得分:-1)
以下是您的计划的更正版本。 addString方法的主要问题是它应该将指针传递给指针,而不仅仅是指针
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
struct program //this is the struct that is in the file program.h
{
int check;
char* title;
char* channel;
};
char* addString(char** destination, char* string); //Replace char* with char**
int main(void)
{
struct program* programs = (struct program*) malloc(sizeof(struct program)); //memory for the struct
addString(&(programs->title), "test123"); //passes the adress of the struct member to the function
printf("%s", programs->title); //and when I print this there is still garbage in it and not the actual string "test"
return 0;
}
char* addString(char** destination, char* string)
{
*destination = (char*) malloc(strlen(string) + 1); //dynamic memory alloction for the length of the string
strcpy(*destination, string); //string copy to the pointer returned from the malloc here above
return 0;
}