使用函数中的字符串到main函数

时间:2013-03-11 22:38:03

标签: c arrays function char c-strings

我的一个函数从文本文件中读取行并存储到变量中。我需要一种方法在我的main函数中使用该变量。我尝试了几种方法,没有任何效果。任何人都可以帮助我吗?

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

int test(const char *fname, char **names){

    char usernames[250][50];
    FILE *infile;
    char buffer[BUFSIZ];
    int i =0;

    infile = fopen(fname, "r");


    while(fgets(buffer,50,infile)){
        strcpy(usernames[i],buffer);
        printf("%s",usernames[i]);
        i++;
    }

    int x, y;
    for(y = 0; y < 250; y++)
        for(x = 0; x < 50; x++)
            usernames[y][x] = names[y][x];

    return 0;
}


int main()
{
    char *names;
    test("test.txt", &names);
}

有人可以帮忙吗?我很长一段时间没用C编码。

1 个答案:

答案 0 :(得分:2)

在C中,调用者应该为它需要的字符串分配内存,否则,没有人知道谁应该释放内存。然后,您可以将指针传递给将填充它的函数。

int main() {
    char names[250][50];
    test("test.txt", names);
    for (int i=0; i < 50; i++) {
        printf("File %d: %s", i, names[i], 250);
    }     
}


void test(const char *fname, char(*names)[50], int maxWords){

    FILE *infile;
    int i =0;
    char buffer[50];

    infile = fopen(fname, "r");

    while(fgets(buffer,50,infile) && i < maxWords){
        strcpy(usernames[i],names[i]);
        i++;
    }    
}