这是我关于堆栈溢出的第一篇文章,我想为我的英语道歉,因为我不是以英语为母语的人。不管怎样,我几乎是自学编程,所以显然我不太擅长。为了获得一些经验,我进行了一些编程练习(从大学 friend 那里得到的),但我在某些练习上遇到了麻烦。该练习要求创建一组由用户提供的 10 个名称,其中一个名称包含其销售额。该程序应将第一个数组的内容传递到另外两个数组中,一个数组的名称已实现超过 6000 次销售,另一个数组的名称尚未成功实现。第一个数组中的人获得 500 的工资奖金,其他人获得 200。程序应该计算他们的奖金的公司总成本并将其打印在屏幕上。该程序还应该打印两个名称数组。
更新:我决定先不使用动态内存分配来解决问题。所以这工作得很好,但由于某种原因它会一直打印姓氏而不是每个姓氏。
#include <stdio.h>
#include <stdlib.h>
int c =0;
int x =0;
int i;
int sum_500 =0;
int sum_200 =0;
char* names_500[10];
char* names_200[10];
char* names[10];
int sales[10];
char buffer[200];
char trash[10];
int main() {
for (i =0; i<10; i++) {
printf("Give name:");
fgets(buffer,201,stdin);
names[i] = buffer;
printf("Give sales profit:");
scanf("%d",&sales[i]);
fgets(trash,11,stdin);
if (sales[i] > 6000) {
names_500[c] = names[i];
sum_500 = sum_500 + 500;
c++;
}
else {
names_200[x] = names[i];
sum_200 = sum_200 + 200;
x++;
}
}
if( c>0) {
for(i =0; i<c; i++) {
printf("%s\n",names_500[i]);
}
}
if (x>0) {
for(i =0; i<x; i++) {
printf("%s\n",names_200[i]);
}
}
printf("Company total bonus cost:%d",sum_200 + sum_500);
return 0;
}
更新:我明白了。看来我将缓冲区变量的指针传递给名称数组,以便它们都打印最后一个字符串。使用 strdup() 可以解决该问题。这是最终代码,包括名称数组的动态内存分配。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int c =0;
int x =0;
int i;
int sum_500 =0;
int sum_200 =0;
char ** names_500;
char ** names_200;
char * name;
int sales[10];
char buffer[40];
char trash[10];
int main() {
for (i =0; i<10; i++) {
printf("Give name:");
fgets(buffer,40,stdin);
name = strdup(buffer);
printf("Give sales profit:");
scanf("%d",&sales[i]);
fgets(trash,11,stdin);
if (sales[i] > 6000) {
names_500= realloc(names_500,(c+1)*sizeof(char*));
names_500[c] = name;
sum_500 = sum_500 + 500;
c++;
}
else {
names_200= realloc(names_200,(x+1)*sizeof(char*));
names_200[x] = name;
sum_200 = sum_200 + 200;
x++;
}
}
if( c>0) {
printf("500 bonus :\n");
for(i =0; i<c; i++) {
printf("%s",names_500[i]);
}
}
if (x>0) {
printf("200 bonus:\n");
for(i =0; i<x; i++) {
printf("%s",names_200[i]);
}
}
printf("Company 200 bonus costs:%d",sum_200 );
printf("\nCompany 500 bonus costs:%d",sum_500);
return 0;
}
最佳答案
The program crashes after entering the first sales number.
程序崩溃的原因是 scanf
的参数中缺少 &
。应该是
scanf("%d",&sales[i]);
旁注:
分配 names[i]
没有任何用处,因为在 names[i] = buffer;
后分配的空间会丢失
names[i] = malloc(strlen(buffer));
names[i] = buffer;
与 names_500[c]
相同
names_500[c] = malloc(strlen(names[i]));
names_500[c] = names[i];
关于c - C 中的输入字符串数组内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20163238/