2013-02-22 43 views
1

我创建了一个双指针并发送地址来分配内存,这需要一个三指针。另外,我正在创建单个指针(目标和辅助)并发送它们的地址来分配内存,这需要双指针。我认为问题在于分配内存,但我无法弄清楚。每当我运行readLinesFromFile函数时,我都会保持seg错误。当我尝试运行allocateMemory函数时,它不会发生段错误。这个问题也可能是在readLinesFromFile功能在将双指针地址传递给三指针时分配内存时遇到问题

int main (int argc, char **argv) 
{ 
    int numPlayers = 0; 
    if (argc != 3) 
    { 
     printf("Missing text file"); 
     return 0; 
    } 
    char **playerNames; 
    int *goals, *assists; 


     FILE *filePtr = fopen(argv[1],"r"); 

     if(filePtr == NULL) 
     { 
      printf("\nFile is empty"); 
      return 0; 
     } 
    numPlayers = countLinesInFile(filePtr); 

    allocateMemory(&goals,&assists,&playerNames,numPlayers); 

    readLinesFromFile(filePtr,goals,assists,playerNames,numPlayers); 


} 


void allocateMemory(int **goals, int **assists, char *** names, int size) 
{ 

    int i = 0; 

    *goals = malloc(MAX_NAME * sizeof(int)); 

    *assists = malloc(MAX_NAME * sizeof(int)); 

    *names = malloc(MAX_NAME * sizeof(char*)); 

    for (i = 0; i < size; i++) 
    { 
     (names[i]) = malloc(MAX_NAME * sizeof(char*)); 
    } 
} 
void readLinesFromFile(FILE *fptr, int *goals, int *assists, char **names, int numLines) 
{ 

    int i = 0, j = 0, x = 0; 

    char players[MAX_LINE]; 

    char *tokenPtr; 

    fptr = fopen(INPUT,"r"); 

    for(i = 0; i < numLines; i++) 
    { 
     fgets(players,MAX_LINE, fptr); 

     tokenPtr = strtok(players," "); 
     strcpy((*(names+i)), tokenPtr); 

     while (tokenPtr != NULL) 
     { 
      tokenPtr = strtok(NULL," "); 
      if (x = 0) 
      { 
       goals[i] = atoi(tokenPtr); 
       x = 1; 
      } 
      else 
      { 
       assists[i] = atoi(tokenPtr); 
       x = 0; 
      } 
     } 
    } 
} 
+0

'(*(*(姓名+ I)=的malloc(大小*的sizeof(字符)))) ;'有一些错位的偏旁。试试'*(*(names + i))= malloc(size * sizeof(char));' – Erik 2013-02-22 23:18:26

+0

我明白你的意思,我改变了它,但它仍然存在段错误:( – user2101171 2013-02-22 23:23:35

+0

只是为了确定,协助成为一个单维数组和名称是一个伪二维数组? – 2013-02-22 23:24:03

回答

0

假设MAX_NAME是一个球员的名字的最大长度,这应该工作:

void AllocateMemory(char *** pppNames, int ** ppGoals, int ** ppAssists, size_t sizePlayersMax) 
{ 
    *pppNames = malloc(sizePlayersMax * sizeof **pppNames); 
    *ppGoals = malloc(sizePlayersMax * sizeof **ppGoals);9 
    *ppAssists = malloc(sizePlayersMax * sizeof **ppAssists); 

    { 
    size_t sizePlayersCount = 0;0 
    for (; sizePlayersCount < sizePlayersMax; ++sizePlayersCount) 
    { 
     (*pppNames)[sizePlayersCount] = calloc(MAX_NAME + 1, sizeof *((*pppNames)[sizePlayersCount])); 
    } 
    } 
} 

为了阻止应用在很长的情况下,重写内存你可能会喜欢的球员的名字来改变这一行:

strcpy((*(names+i)), tokenPtr); 

成为:

if (tokenPtr) 
    strncpy((*(names+i)), tokenPtr, MAX_NAME); 

这会截断存储的玩家名称,最大值为MAX_NAME个字符。后者是尺寸AllocateMemory()使用减号10/NUL需要这个备用字符来终止字符数组,以便它可以用作“字符串”。

最后也这是危险的:

while (tokenPtr != NULL) 
{ 
    tokenPtr = strtok(NULL," "); 

    if (x = 0) 
    { 

更好地这样做:

while (NULL != (tokenPtr = strtok(NULL," "))) 
{ 
    if (x = 0) 
    {