我正在写一个关于USACO的小程序。
问题以http://usacotraining.blogspot.co.uk/2013/09/problem-112-greedy-gift-givers.html形式发布
这是我的代码:
/*
ID: xin.sun2
LANG: C
TASK: gift1
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int searchIndex(char *list[], char* s, int size) {
for (int i = 0; i < size; i ++) {
if (strcmp(list[i], s) == 0) {
return i;
}
}
return -1;
}
int main() {
freopen("gift1.in", "r", stdin);
freopen("gift1.out", "w", stdout);
int num_people = 0;
scanf("%d", &num_people);
char *nameList[num_people] = malloc(num_people*100*sizeof(char));
int money[num_people];
memset(money, 0, num_people*sizeof(int));
for (int i = 0; i < num_people; i++)
scanf("%s", nameList[i]);
char* this_people = malloc(100*sizeof(char));
while (scanf("%s", this_people) != EOF) {
int amount, num_giving, people_index;
people_index = searchIndex(nameList, this_people, num_people);
scanf("%d", &amount);
scanf("%d", &num_giving);
money[people_index] -= amount/num_giving*num_giving;
int giving_amount = amount/num_giving;
for (int i = 0; i < num_giving; i++) {
char* p = malloc(100*sizeof(char));
scanf("%s",p);
int this_index = searchIndex(nameList, p, num_people);
money[this_index] += giving_amount;
}
}
for (int i = 0; i < num_people; i++) {
printf("%s %d\n", nameList[i], money[i]);
}
return 0;
}当我编译.c文件时,它没有问题,但在执行文件时没有问题。它显示了分段错误11。我尝试使用gdb,结果是
Program received signal SIGSEGV, Segmentation fault.
0x00007fff96b17908 in ?? ()我有两个问题: 1.我的代码(算法)出了什么问题?这可能是语法问题,因为我对c++编程2非常陌生。为什么gdb会显示??(),而不是主程序中的行号。我是不是用错了gdb?
谢谢大家!
更新
我纠正了不对数组和字符的空间进行签名的问题。但是有一个编译错误
null.c:27:8: error: variable-sized object may not be initialized
char *nameList[num_people] = malloc(num_people*100*sizeof(char));我想知道初始化字符串数组的正确方法,以及如何将字符串数组作为参数传递给函数。
发布于 2014-02-22 15:42:00
char* this_people;
while (scanf("%s", this_people) != EOF) {和
char* p;
scanf("%s",p);是错误的,this_people和p指向任何地方,并使用这个“无处”作为输入缓冲区。要么使用malloc()分配一些内存,要么使p成为一个数组。(如果用户输入比您提供的空间更长的内容,您仍然会遇到问题,但随着您的学习,这将是一个问题,直到稍后)。
当您遇到类似的问题时,gdb命令bt是您的朋友。它显示崩溃后从何处调用了哪些函数。
对于namelist数组,要使用:
界定:
char **namelist;
namelist=malloc(num_people*sizeof (char *));或者,但这需要“新”编译器,因为在旧的C规范中不是这样的:
char *namelist[num_people];然后,在这两种情况下,每一种情况:
for (i=0; i<num_people; i++)
namelist[i]=malloc(100);(您应该检查malloc是否返回NULL并抛出一个错误,但为了简洁起见,我省略了这个错误)。
发布于 2014-02-22 15:42:53
char* this_people;
while (scanf("%s", this_people) != EOF) {this_people需要存储空间。属于形式
char this_people[100]; //or some desired maximum storage
while (scanf("%s", this_people) != EOF) {另外,
char *nameList[num_people];分配一堆类型为char *的指针。没有任何储藏物。
发布于 2014-02-22 16:03:04
malloc()动态地为它们分配内存,或者使用scanf("%ms", &p),让glibc为您进行内存分配。?? ()而不是行号和函数名,因为它没有足够的信息来显示它们。要解决这个问题,您需要使用-g编译您的程序(我想您正在使用gcc),并为您的程序所需的系统库(在本例中为glibc)安装调试信息包。如果使用的是Fedora或CentOS,则可以通过debuginfo-install glibc为glibc安装调试信息包。https://stackoverflow.com/questions/21956442
复制相似问题