[英]Struct member char * initialized in a function call as a parameter
這更多是出於好奇,而不是我想要或需要它的方式。 但是,當我做一些樣機並想測試某些東西時,我最終得到了這樣的東西……並且想知道為什么它不能按我預期的那樣工作。
typedef struct {
char *a;
char *b;
char *c;
}mystruct;
void init_chars (char *arg)
{
arg = malloc (sizeof (char)*10);
arg = "0123456789";
printf ("%s\n", arg);
}
int main ()
{
mystruct *msp = malloc (sizeof (mystruct));
init_chars (msp->a);
init_chars (msp->b);
init_chars (msp->c);
printf ("%s, %s, %s\n", msp->a, msp->b, msp->c);
return 0;
}
打印...
0123456789
0123456789
0123456789
(null),(null),(null)
將值傳遞給函數參數時,C中有兩件事
您正在按值傳遞,因此您要將一些未初始化的值傳遞給該函數,並在該函數外部看不見的函數中對其進行初始化,因此您試圖在main()
使用未初始化的值,這將導致未定義的行為。
arg = "0123456789";
如果要將字符串復制到某個內存位置,則需要memcpy()
或strcpy()
注意:使用未初始化的值會導致未定義的行為。
您的代碼有幾個問題。 這是固定代碼:
/* Don't forget to include <stdio.h>, <stdlib.h> and <string.h> */
typedef struct {
char *a;
char *b;
char *c;
}mystruct;
void init_chars (char **arg) /* This should be char** as the address of a char* is passed */
{
*arg = malloc ( /*sizeof(char)* */ 11); /* sizeof(char) is 1 always. You don't need it */
/* Note the change of `arg` to `*arg` too */
/* And that I've used 11 and not 10 because there needs to be space for the NUL-terminator */
if(*arg == NULL) /* If the above malloc failed */
{
printf("Oops! malloc for *arg failed!");
exit(-1);
}
//arg = "0123456789"; /* You just lost the allocated memory as you make the pointer point to a string literal */
strcpy(*arg, "0123456789"); /* Use strcpy instead */
printf ("%s\n", *arg); /* *arg here */
}
int main ()
{
mystruct *msp = malloc (sizeof (mystruct));
if(msp == NULL) /* If the above malloc failed */
{
printf("Oops! malloc for msp failed!");
return -1;
}
init_chars (&(msp->a));
init_chars (&(msp->b));
init_chars (&(msp->c)); /* Pass address of variables rather than their value */
printf ("%s, %s, %s\n", msp->a, msp->b, msp->c);
free(msp->a);
free(msp->b);
free(msp->c);
free(msp); /* Free everything after use */
return 0;
}
typedef struct {
char *a;
char *b;
char *c;
}mystruct;
void init_chars (char **arg)
{
*arg = malloc (sizeof (char)*11);
if(*arg == NULL)
{
printf("malloc failed!");
exit(-1);
}
strcpy(*arg,"0123456789");
printf ("%s\n", *arg);
}
int main ()
{
mystruct *msp = malloc (sizeof (mystruct));
if(msp == NULL)
{
printf("malloc failed");
exit(-1);
}
init_chars (&msp->a);
init_chars (&msp->b);
init_chars (&msp->c);
printf ("%s, %s, %s\n", msp->a, msp->b, msp->c);
free(msp->a);
free(msp->b);
free(msp->c);
free(msp)
return 0;
}
輸出:
0123456789
0123456789
0123456789
0123456789、0123456789、0123456789
與您的代碼進行比較,您將理解為什么
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.