我怎样才能在while循环之外访问数组

时间:2014-06-26 09:36:19

标签: c arrays

如何访问在while循环中填充的循环外的数组?

Main.c

#define _CRT_SECURE_NO_WARNINGS

#include "Definition.h"
#include <stdio.h>
#include <string.h>
#include <pthread.h>

extern int Readline(),CountWord();

char Line[500];  /* one line from the file */
char myFileList[300][MaxLine];
char myFileList2[300][MaxLine];
char myFileList3[300][MaxLine];
char myFileList4[300][MaxLine];

int NChars = 0,  /* number of characters seen so far */
    NWords = 0,  /* number of words seen so far */
    NLines = 0,  /* number of lines seen so far */
    LineLength;  /* length of the current line */ 


void *ThreadTask(void *threadarg)
{
//receive array
//match each element with file name in directory
//perform counts on each file
//print store or return values 

//printf("%s",myFilesList);

}    

FILE *filep;

int main(int argc, char **argv)  
{
    int i = 0;
    filep = fopen(argv[1], "r");
    if (!filep){
        printf("No %s such file found\n", argv[1]);
        return -1;
    }
    while ((LineLength = Readline(filep))!=0) //here in this loop I split a big file into 4 arrays depending on the number of lines(240). How can I access these newly created arrays outside the while loops. I need to pass them to individual threads as arguments. 
    {
        if(i>=0 && i<60){
        strcpy(myFileList[i], Line);
        printf("%s\n", myFileList[i]);
        i++;
        }           

        if(i>=60 && i<120){
        strcpy(myFileList2[i], Line);
        //printf("%s\n", myFileList2[i]);
        i++;}


        if(i>=120 && i<180){
        strcpy(myFileList3[i], Line);
        //printf("%s\n", myFileList3[i]);
        i++;}

        if(i>=180){
        strcpy(myFileList4[i], Line);
        //printf("%s\n", myFileList4[i]);
        i++;}


    }       

    fclose(filep);      
}

Readline.c

#include "Definition.h"
#include "ExternalVar.h"
#include <stdio.h>

int Readline(FILE *filep)
{
//Please implement your code here
    int i = 0;
    char ch;

    while (!feof(filep) && i<MaxLine){
        ch = fgetc(filep);
        if (ch == '\n'){
            break;
        }           
        Line[i] = ch;           
        i++;

    }

    Line[i] = 0;
    return i;
}

最简单的方法是将while循环中创建的四个数组作为参数传递给线程吗?我每次尝试打印while循环之外的数组都没有什么,当我尝试在while循环内打印出来但在if循环之外时,它们只显示第一行60次。

2 个答案:

答案 0 :(得分:0)

如果使用PThreads,请使用pthread_create()的最后一个参数将参数传递给胎面功能。

答案 1 :(得分:0)

您必须将指向数组的指针传递给ReadLine ...最好传递最大长度,以避免缓冲区溢出错误。

#define MAXLEN 240

char Line[MAXLEN+1];

while ((LineLength = Readline(filep, Line, MAXLEN))!=0)
{
  ...
}


int Readline(FILE *filep, char *Line, int maxlen)
{
   ...
相关问题