gpt4 book ai didi

c - 指针未初始化的问题

转载 作者:行者123 更新时间:2023-11-30 16:27:08 25 4
gpt4 key购买 nike

我正在尝试制作一个程序,询问用户姓名以及他们欠公司的金额。问题是,每次我尝试编译程序时,都会收到此警告,提示“用户可能未初始化”。我不太确定这意味着什么。对我做错了什么有帮助吗?谢谢!

#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;
}

最佳答案

结构信息*用户;

这会分配一个指向用户结构的指针,而不是结构本身。

因此,您可以通过struct info user;在堆栈上分配它并将 &user 传递给函数,或通过 user = (struct info*)malloc( sizeof(struct info) ) 动态分配它。

无论哪种方式都应该避免段错误(因为指针未初始化)。..)

关于c - 指针未初始化的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52845596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com