【发布时间】:2016-06-28 07:08:46
【问题描述】:
我正在为学校做一个项目,但我无法将结构的动态数组传递给 c 中的另一个函数。该函数只是应该检查结构的一个元素,如果该数组的元素等于当前元素,则返回已经添加的元素。我也无法声明接受 calloc 数组的函数。任何帮助,将不胜感激!我整晚都在寻找解决方案。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
struct EDGETAG;
typedef struct
{
char c;
bool isVisited;
struct EDGETAG* p;
} VERTEX;
typedef struct EDGE
{
VERTEX* v;
struct EDGETAG* q;
} EDGE;
int main(int argc, char* argv[])
{
int a;
struct VERTEX *vert = (VERTEX*)calloc(100, sizeof (VERTEX*));
char s;
int count = 0;
FILE* input = fopen(argv[1],"r");
while((a = fgetc(input)) != EOF)
{
if(isspace(a)==0)
{
s = a;
printf("%c ",s);
determiner(s,vert,count);
count++;
}
}
return 0;
}
以及被调用的函数
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
typedef struct VERTEX
{
char c;
bool isVisited;
struct EDGETAG* p;
} VERTEX;
typedef struct EDGETAG
{
VERTEX* v;
struct EDGETAG* q;
} EDGE;
void determiner (char a, struct VERTEX *vert, int count)
{
int i;
for(i=0;i < count; i++)
{
if(vert[i].c == a)
{
printf("%c allready added ",vert[i].c);
return ;
}
else
{
VERTEX* new1 = (VERTEX*)malloc(sizeof(VERTEX));
new1->c = a;
vert[i] = *new1;
}
}
return ;
输入是: 甲乙 乙丙 前任 光盘 交流电 输出:A B B B allready added C E X C D A C
【问题讨论】:
-
I can't pass a dynamic array有什么问题? -
你应该从
determiner返回一个布尔值来指示元素是否被找到或新分配,只有在后一种情况下count才应该增加,否则你会访问未初始化的内存 -
你想创建一个顶点链表吗?你确定它们应该在一个数组中吗?
-
为什么标题中没有类型定义?他们应该是。干燥——不要重复自己。并且请学会以正统的方式缩进你的代码。它极大地提高了人们发现您的问题的机会。
标签: c arrays dynamic struct calloc