使用指针的二维数组

发布于 2024-09-27 13:31:59 字数 1968 浏览 1 评论 0原文

我正在尝试读取一个具有一些随机名称的文件,格式为“ADAM”、“MARK”、“JESSIE”.....

我有一些限制,该文件应该在函数中读取,但应该可以从主函数中访问没有全局变量的函数。 文件大小和文件中的名称数量未知。 这就是我到目前为止所做的。我对动态二维数组有一些困难,因为我没有太多使用它们。

/* Function to read from the file */
int read_names(FILE *input, char ***names, int *name_count)
{
    int f1,size,count,i,j=0;
    char **name_array,*text,pos=0;
    /* get the file size */
    f1=open("names.txt",O_RDONLY);
    size=lseek(f1,0,SEEK_END);
    close(f1);
    /* Reading all the characters of the file into memory */
    //Since file size is known we can use block transfer
    text=(char *) malloc(size * sizeof(char) );
    fscanf(input,"%s",text);

    /* Finding the no of names in the file */
    for(i=0;i<size;i++)
    {
        if(text[i]==',')
            count++;
    }
    printf("No. of names determined\n");

    /* Assigning the Name count to the pointer */
    name_count=(int*)malloc(sizeof(int));
    *name_count=count;


    name_array=(char **) malloc(count * sizeof(char *));
    for(i=0;i<count;i++)
    {
        name_array[i]=(char*) malloc(10 *sizeof(char ));
    }
    for(i=0;i<size;i++)
    {
        if(text[i]!='"')
            if(text[i]==',')
            {
                **name_array[pos][j]='\0'; //error here
                pos++;
                j=0;
            }
            else
                name_array[pos][j++]=text[i];
    }
    printf("Names Counted\n");
    printf("Total no of names: %d\n",*name_count);
    names=(char ***) malloc(sizeof(char **);
    names=&name_array;
    return 1;
}

/* Main Function */
int main(int argc, char *argv[])
{
    FILE *fp;
    char ***names;
    int *name_count;
    int status;
    // Opening the file
    fp = fopen("names.txt","r");
    // Now read from file
    status = read_names(fp,names,name_count);
    printf("From Main\n");
    fclose(fp);
    system("PAUSE");
    return 0;
}

我使用 WxDev 并在尝试分配空字符时收到错误“‘unary *’的类型参数无效。

有关如何执行此操作的任何指示吗?

I am attempting to read a file with some random names in the format "ADAM","MARK","JESSIE" .....

I have some constraints, the file should be read in a function but should be accessible form the main function with no global variables.
The file size and the no of names in the file are not known.
This is what I have done till now. I have some difficulty with dynamic 2d array as I have not used them much.

/* Function to read from the file */
int read_names(FILE *input, char ***names, int *name_count)
{
    int f1,size,count,i,j=0;
    char **name_array,*text,pos=0;
    /* get the file size */
    f1=open("names.txt",O_RDONLY);
    size=lseek(f1,0,SEEK_END);
    close(f1);
    /* Reading all the characters of the file into memory */
    //Since file size is known we can use block transfer
    text=(char *) malloc(size * sizeof(char) );
    fscanf(input,"%s",text);

    /* Finding the no of names in the file */
    for(i=0;i<size;i++)
    {
        if(text[i]==',')
            count++;
    }
    printf("No. of names determined\n");

    /* Assigning the Name count to the pointer */
    name_count=(int*)malloc(sizeof(int));
    *name_count=count;


    name_array=(char **) malloc(count * sizeof(char *));
    for(i=0;i<count;i++)
    {
        name_array[i]=(char*) malloc(10 *sizeof(char ));
    }
    for(i=0;i<size;i++)
    {
        if(text[i]!='"')
            if(text[i]==',')
            {
                **name_array[pos][j]='\0'; //error here
                pos++;
                j=0;
            }
            else
                name_array[pos][j++]=text[i];
    }
    printf("Names Counted\n");
    printf("Total no of names: %d\n",*name_count);
    names=(char ***) malloc(sizeof(char **);
    names=&name_array;
    return 1;
}

/* Main Function */
int main(int argc, char *argv[])
{
    FILE *fp;
    char ***names;
    int *name_count;
    int status;
    // Opening the file
    fp = fopen("names.txt","r");
    // Now read from file
    status = read_names(fp,names,name_count);
    printf("From Main\n");
    fclose(fp);
    system("PAUSE");
    return 0;
}

I use WxDev and am getting an error "invalid type argument of `unary *' when I try to assign the null character.

Any pointers on how to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

寄意 2024-10-04 13:31:59

从生成错误的行仔细查看此表达式,并思考它在做什么:

**name_array[pos][j]

记住括号具有更高的 优先级高于一元 *,这相当于 *(*((name_array[pos])[j])),即 2 个下标后跟 2 个取消引用。总共有 4 次取消引用,因为 foo[i] 相当于 *(foo+i)name_array 的声明类型为 char **,这意味着您只能取消引用它两次。将类型声明 char **name_array 视为表示 **name_array 具有类型 char,因为这是类型声明语法的基础(请参阅C 的历史,“胚胎 C”)。

题外话

另一个问题出现了:

name_array[i]=(char*) malloc(sizeof(char ));

在这里,您只为 name_array 的每个元素中的单个字符分配足够的空间。

Take a closer look at this expression from the line generating the error and think about what it's doing:

**name_array[pos][j]

Remembering that brackets have higher precedence than unary *, this is equivalent to *(*((name_array[pos])[j])), which is 2 subscripts followed by 2 dereferences. That's a total of 4 dereferences, since foo[i] is equivalent to *(foo+i). The declared type of name_array is char **, which means you can only dereference it twice. Think of the type declaration char **name_array as meaning that **name_array has type char, since that's the basis for type declaration syntax (see the History of C, "Embryonic C").

Off topic

Another issue arises on the line:

name_array[i]=(char*) malloc(sizeof(char ));

Here, you're only allocating enough space for a single character in each element of name_array.

尘世孤行 2024-10-04 13:31:59
            **name_array[pos][j]='\0'; \\error here

我看到 name_array 被声明为

char **name_array

问题是

**name_array[pos][j] 尝试取消引用(两次!!)一个字符

**   (name_array[pos]) [j];    /* name_array[pos] is of type (char*) */
** ( (name_array[pos]) [j] );  /* name_array[pos][j] is of type (char) */

您不能取消引用一个字符。

建议:简化代码。
当代码没有“表现”时,通常不是因为它太简单;)

            **name_array[pos][j]='\0'; \\error here

I see that name_array is declared as

char **name_array

Problem is that

**name_array[pos][j] tries to dereference (twice!!) a character

**   (name_array[pos]) [j];    /* name_array[pos] is of type (char*) */
** ( (name_array[pos]) [j] );  /* name_array[pos][j] is of type (char) */

You cannot dereference a character.

Suggestion: simplify your code.
When code doesn't "behave", it usually is not because it is too simple ;)

↘紸啶 2024-10-04 13:31:59

这可能看起来很迂腐,但却很重要。您没有使用二维数组。事实上,您不会在代码中创建ANY 数组。

需要理解的重要事情之一是数组“衰减”为指针。

链接文字

C 中围绕数组和指针的大部分混淆都可以追溯到对这句话的误解。说数组和指针是等价的”并不意味着它们是相同的,甚至也不意味着它们可以互换。它的意思是定义了数组和指针算术,以便可以方便地使用指针来访问数组或模拟数组。换句话说,正如 Wayne Throop 所说,指针算术和数组索引在 C 中是等效的,而指针和数组是不同的。'')

This might seem pedantic, but it is important. You aren't using a 2D array. In fact, you don't create ANY arrays in your code.

One of the important things to understand is that arrays "decay" into pointers.

link text

Much of the confusion surrounding arrays and pointers in C can be traced to a misunderstanding of this statement. Saying that arrays and pointers are equivalent'' means neither that they are identical nor even interchangeable. What it means is that array and pointer arithmetic is defined such that a pointer can be conveniently used to access an array or to simulate an array. In other words, as Wayne Throop has put it, it'spointer arithmetic and array indexing [that] are equivalent in C, pointers and arrays are different.'')

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文