【发布时间】:2013-04-17 06:09:34
【问题描述】:
所以我有这段代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hw09-header.h"
struct student
{
char* name;
char* course;
};
int main(int argc, char* argv[])
{
int i = 0, init_size=10,x,z;
char *value = "go";
int key, count=0;
char* del = ","; /*Uses comma sign as delimiter*/
char *token=NULL;
char *temp_stor;
struct student *array;
struct student *temp;
if(argc != 2)
{
printf(" usage: program_name positive_integern");
printf("example: ./example-hw09 123n");
exit(1);
}
/************** begin REQUIRED **************/
/* put before logic. DO NOT PUT IN A LOOP */
key = atoi(argv[1]);
initialize(key);
/************** end REQUIRED **************/
/* example loop */
array=malloc((init_size)*sizeof(int));
while(strcmp(value, "stop") != 0)
{
value = getString();
token = strtok(value, del);
while (token !=NULL)
{
if(i%4==0)
{
init_size=init_size*2;
temp = realloc(array,init_size*sizeof(int)) ;
if(temp != NULL)
{
array = temp;
}
else
{
printf("unable to reallocaten");
exit(1);
}
}
array[i].name=malloc(sizeof(struct student)*10);
strcpy(array[i].name,token);
printf("%s %dn",array[i].name,i);
token = strtok( NULL, del );
array[i].course=malloc(sizeof(struct student)*11);
strcpy(array[i].course,token);
printf("%s n",array[i].course);
i=i+1;
token = strtok( NULL, del );
x=i;
for(x=0; x<i; x++)
{
if(strcmp(array[x].name,token)==0)
printf("Duplicate found n");
}
}
}
}
现在当我尝试执行 strcmp 时,它总是给我一个分段错误,我不知道为什么。
我不应该在这里使用链表,我想我已经完成了所有的事情,对于接下来的几部分我只需要比较和排序,我不断收到分段错误。
我的数组中确实有元素,我可以将它们全部打印出来,只是出于某种原因不比较它们。
【问题讨论】:
-
你确定学生的名字只有9个字符吗?
-
请重新粘贴您的代码并删除标签(将您的编辑器配置为仅使用空格并重新缩进)。还要编译你的代码并启用警告(对于 gcc
-Wall -Wextra),看看你是否从编译器得到任何提示。 -
是的,这是作业的一部分,名称不会超过 9 个字母。
-
你说得对,token是NULL......
-
您的内存分配似乎几乎是随机选择的 - 您是否了解当您执行以下操作时发生了什么:
array=malloc((init_size)*sizeof(int));或array[i].name=malloc(sizeof(struct student)*10);?因为用于计算分配大小的表达式似乎与您分配分配的指针的类型没有太大关系。