[英]Command Flow in C, function call after printf
所以我有這個超級簡單的 C 代碼在這里接受用戶輸入並將其打印出來,然后是“T-Plus”while循環。 在這種情況下,我選擇了一個隨機名稱來測試“哇”,但不會調用 while 循環。 我的問題是,為什么在 printf() function 之后不調用“T-Plus: %d\n”while 循環打印?:
#include <stdio.h>
char getString();
void tcount(void);
int main(void)
{
tcount();
}
void tcount(void)
{
// class scanf user input
printf("%s", getString());
int i = 1;
do
{
printf("T-Plus: %d\n", i);
i++;
} while( i < 51 );
}
char getString()
{
char name;
printf("Please a string name: \n");
scanf("%s", &name);
return name;
}
現在當我運行它時,它變成了 output:
$ ./namecount
Please a string name:
whoa
但不會調用 T-Plus: 字符串。
我在這里看到兩個問題:
1)在 function getString()
中,您嘗試讀取/掃描字符中的字符串,您需要 memory 來存儲字符串和終止字符,因此您可以使用這兩種方式中的任何一種
使用 char 數組,例如char name[50];
或者
使用 char 指針並使用 malloc 分配 memory 例如char *p_name = malloc(sizeof(char)*50);
2)然后您嘗試返回存儲在局部變量中的這個字符串(一旦 function 結束,它將被銷毀)所以您應該使用第二種方法(使用 malloc)並返回指針。
所以你的代碼看起來像:
#include <stdio.h>
#include <stdlib.h>
char * getString();
void tcount(void);
int main(void)
{
tcount();
}
void tcount(void)
{
// class scanf user input
char *p_name = getString();
printf("%s", p_name);
free(p_name);
int i = 1;
do
{
printf("T-Plus: %d\n", i);
i++;
} while( i < 51 );
}
char *getString()
{
char *p_name = malloc(sizeof(char)*50);
printf("Please a string name: \n");
scanf("%s", p_name);
return p_name;
}
上面的答案沒有用,好的,所以我已經編輯了這樣的代碼,它編譯得很好。 但是會引發分段錯誤。
#include <stdio.h>
#include <stdlib.h>
char * getString();
void tcount(void);
int main(void)
{
tcount();
}
void tcount(void)
{
// class scanf user input
char *name = getString();
printf("%s", name);
free(name);
int i = 1;
do
{
printf("T-Plus: %d\n", i);
i++;
} while( i < 51 );
}
char * getString()
{
char *p_name[50];
printf("Please a string name: \n");
scanf("%49s", (char *) &p_name);
return *p_name;
}
當程序運行時,它會詢問您的輸入,但仍會引發分段錯誤(核心轉儲)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.