[英]Trouble with a pointer not being initialized
我正在嘗試制作一個程序,要求用戶名和他們欠公司的錢。 問題是,每次我嘗試編譯程序時,都會收到此警告,提示“用戶可能未初始化”。 我不太確定那是什么意思。 對我做錯了什么有幫助嗎? 謝謝!
#define END '\0'
#define LENGTH 20
struct info
{
char lastName[LENGTH];
float payment;
};
int customerS();
void accounts(struct info *userStart, int amount);
void changeNames(struct info *userStart, int amount);
void sort(struct info *userStart, int amount);
void results(struct info *userStart, int amount);
int main()
{
struct info *user;
int amount;
while((amount = customers()) != 0)
{
accounts(user, amount);
changeNames(user, amount);
sortNames(user, amount);
results(user, amount);
free(user);
}
return 0;
}
int customers()
{
int choice;
do
{
printf("\nHow many customers do you have (2 to 300, 0=quit): ",
scanf("%d", &choice);
}
while((choice < 2|| choice > 300) && choice != 0);
return choice;
}
void accounts(struct info *userStart, int amount)
{
struct info *user;
char *name[LENGTH];
float owed;
for(user = userStart; (user - userStart) < amount; user++)
{
scanf (" %s", name[LENGTH]);
getchar();
do
{
name[LENGTH] = getchar();
name[LENGTH]++;
}
while(!('\n'));
user->lastName[LENGTH + 1] = END;
scanf("%f", &owed);
user->payment = owed;
}
return;
}
void changeNames(struct info *userStart, int amount)
{
char *fast = &userStart->lastName[LENGTH],
*slow = &userStart->lastName[LENGTH];
if(tolower(*fast))
*slow++ = toupper(*fast);
while(*fast != END)
{
if(!isspace(*fast) || isalpha(*fast))
*slow++ = tolower(*fast);
fast++;
}
*slow = END;
return;
}
void sort(struct info *userStart, int amount)
{
struct info *user;
char *in,
*out,
temp;
for(out = user->lastName; (out - userStart->lastName) < amount; out++)
{
for(in = out + 1; (in - userStart->lastName) < amount; in++)
{
if(strcmp(user->lastName, userStart->lastName))
{
temp = *out;
*out = *in;
*in = temp;
}
}
}
return;
}
void results(struct info *userStart, int amount)
{
struct info *user;
printf("\nName: %s Payment: $%.2f", user->lastName, user->payment);
return;
}
結構信息* user;
這會分配指向用戶結構的指針,而不是結構本身。
因此,您可以通過struct info user;
將其分配到堆棧上struct info user;
並將&user傳遞給函數,或通過user = (struct info*)malloc( sizeof(struct info) )
動態分配它。
兩種方法都應避免分段錯誤(因為指針未初始化)。 ..)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.