2015-04-30 76 views
1

好吧,所以我们应该提示用户输入25000行文本。 每行包含三个整数。然后,我们将该行中的第三个整数传递给另一个结构,并连接每个整数,直到有25000个互连整数。C:使用strcpy将一个结构元素转换为数组

这是我已经试过:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

typedef struct graph{ 
    int begin; 
    int end; 
    int cost; 
} PathEdge; 
int comp_fcn(const void *a, const void *b) { 
    return ((PathEdge *) a)->cost - ((PathEdge *) b)->cost; 
} 
int main(void) 
{ 
    int nlines,i; 
    char r; 
    int ecost,ebegin,eend; 
    scanf("%d",&nlines); 
    PathEdge edges[nlines+1]; 
    for(i=0;i<nlines;i++) 
    { 
     scanf("%d, %d, %dn",&ebegin, &eend, &ecost); 
     edges[i].begin = ebegin; 
     edges[i].end = eend; 
     edges[i].cost = ecost; 
     struct town 
     { 
      struct town *north; 
      int name[25000]; 
     }; 
     struct town *root, *current; 
     root = malloc(sizeof(struct town)); 
     root->north = NULL; 
     strcpy (root->name,ecost); 
     current = malloc(sizeof(struct town)); 
     current->north = root; 
     strcpy (current->name,ecost); 
    } 
    printf("Please enter a node that you want to examine. If you want to exit, please press 'X'.n"); 
    scanf("%c",&r); 
    switch(r) 
    { 
     case 'X': 
     case 'x': 
     printf("You entered a wrong value. Gomen. Try againn."); 
     break; 
     default: 
     if((0<r)&&(r<25000)) 
     { 
      printf("You have accessed node %dn",r); 
      printf("Its neighboring nodes are %dn",edges[r].cost); 
      printf("Its neighboring nodes are %dn",edges[i].cost); 
     } 
     else 
     { 
      printf("Invalid input again. Please do try again. Thanksn"); 
     } 
     break; 
    } 
    return 0; 
} 

而且有警告... “从兼容的指针类型传递的strcpy的参数1” “路过的strcpy的参数2,使指针从整数无强制转换“ 期望的char * __ restrict __但参数的类型为'int' 加上当我输入25000行文本时,发生分段错误。请帮忙。谢谢!

+1

您可能并不着急。用户将长时间输入25000 * 3整数:) –

+0

将'scanf(“%c”,&r);''改为'scanf(“%c”,&r);'以避免明显的下一个问题。:-) –

+0

Vlad从莫斯科,我们得到一个文本文件包含这些25000行的文本:)我们只需要输入它使用./test

回答

2

strcpy是复制(即零终止字节char“阵列”),你也许应该使用memcpy代替。

或者,如果你只是想一个整数分配到阵列中的一个元素,使用普通的分配:

current->name[someIndex] = ecost; 

或者,也许你打算将name成员应该是 ?那么你应该使用一个字符数组而不是整数。您需要将整数值转换为字符串,例如, sprintf

sprintf(current->name, "%d", ecost); 
0

您可以使用itoa转换成整数,字符串和字符串复制到根 - >名称。

char str[20]; 

itoa(ecost, str, 10); 

strcpy(root->name, str);