2016-05-31 16 views
0

这是我的问题:我必须为学校制作此程序,并且我花了最后一个小时进行调试和搜索,并且没有找到答案。使用引用参考的结构数组

我在我的main中有一个结构数组,我想给我的函数seteverythingup(通过引用调用)给出该数组,因为在此函数中我从文件中读取的字符串被拆分,并且我想写它进入结构,但当strcpy与struct数组时,我总是得到一个SIGSEV错误。

这是我的主:

int main(int argc, char *argv[]) 
{ 
FILE* datei; 
int size = 10; 
int used = 0; 
char line[1000]; 
struct raeume *arr = (raeume *) malloc(size * sizeof(raeume*)); 
if(arr == NULL){ 
    return 0; 
} 
if(argc < 2){ 
    return 0; 
} 
datei = fopen(argv[1], "rt"); 
if(datei == NULL){ 
    return 0; 
} 
fgets(line,sizeof(line),datei); 
while(fgets(line,sizeof(line),datei)){ 
     int l = strlen(line); 
     if(line[l-1] == '\n'){ 
      line[l-1] = '\0'; 
     } 
      seteverythingup(&line,arr,size,&used); 

} 
ausgabeunsortiert(arr,size); 
fclose(datei); 
return 0; 
} 

,这是我的函数:

void seteverythingup(char line[],struct raeume *arr[], int size,int used) 
{ 
    char *token,raumnummer[5],klasse[6]; 
    int tische = 0; 
    const char c[2] = ";"; 
    int i=0; 
    token = strtok(line, c); 
    strcpy(raumnummer,token); 
    while(token != NULL) 
    { 
     token = strtok(NULL, c); 
     if(i==0){ 
      strcpy(klasse,token); 
     }else if(i==1){ 
      sscanf(token,"%d",&tische); 
     } 
     i++; 
    } 
    managesize(&arr[size],&size,used); 
    strcpy(arr[used]->number,raumnummer); 
    strcpy(arr[used]->klasse,klasse); 
    arr[used]->tische = tische; 
    used++; 
} 
+0

从技术上讲,C没有引用调用,只能按值调用。通过使用指向变量的指针,可以*通过引用来模拟*调用。 –

+1

至于你的问题,如果你的代码不会导致编译器给你错误或警告,你需要启用更多的警告。 –

+0

您分配了一个指针数组,但指针指向的内容没有空间。 – stark

回答

0

编辑:既然有更多的困惑我写了一个小程序,工程出部分你遇到麻烦了。

#include <cstdlib> 

struct raeume { 
    int foo; 
    int bar; 
}; 

void seteverythingup(struct raeume *arr, size_t len) { 
    for (size_t i = 0; i < len; ++i) { 
     arr[i].foo = 42; 
     arr[i].bar = 53; 
    } 
} 

int main() { 
    const size_t size = 10; 
    struct raeume *arr = (struct raeume*) malloc(size * sizeof(struct raeume)); 

    seteverythingup(arr, size); 

    return 0; 
} 

所以基本上你的函数的签名有点奇怪。 Malloc返回一个指向内存位置的指针。所以你真的不需要一个指向数组的指针。只需将你从malloc得到的指针传递给该函数,该函数就可以操作该区域。

原来的答案:

malloc(size * sizeof(raeume*)); 

这可能是给你一个很难的代码的一部分。 sizeof返回一个类型的大小。你问sizeof指向你raeume结构需要的指针有多少个字节。你可能想要做的是要求结构本身的大小,并为此分配大小乘以空间。因此,正确调用malloc将是:

malloc(size * sizeof(struct raeume)); 
+0

非常感谢您解决了一个问题,我甚至都不知道自己做得很好,但我仍然无法确定为什么当我给它我的功能。在我的主要工作完全正常,但在我的功能,它只是说:0xbaadf00d当我看看数组的内存 –

+0

好吧,没关系,我只是想出了很多感谢! –

+0

好吧,太棒了。自从您要求更多帮助以来,我已经扩大了我的答案。请考虑将回答标记为已回答。 – datosh