简体   繁体   中英

Passing array of pointers into a function

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


void getline(char *line, int lim)
{
    int len = 0;
    char c;
    while (len < lim)
    {
        if ((c=getchar()) != EOF && c != '\n')
        {
            *line++ = c;
            printf("reading %c\n", c);
            len++;
        }
        else
            break;
    }

    *line = '\0';
}


int main()
{
    char (*lines)[500]; // pointer to array with 500 chars
    char *linetwo[4]; //why doesnt this work????  array of 4 pointers.


    getline(*lines, 500);
    getline(*linetwo, 500); // !!!!ERROR!!!

    printf("%s", *lines);

    system("PAUSE");
    return 0;

}

I'm having trouble with this code. I want four lines of input with each lines having maximum 500 chars. I wrote a getline function to save it to a char * pointer. However, getline gives error when I initialize an array of pointers.

The only difference between (*lines)[500] and *lines[4] is, I think, whether it does not specify either the number of lines or the number of chars in a line.

Please help me understand why passing *linetwo into getline after *linetwo[4] initialization gives error.

Your pointers don't point to anything, yet you use them as if they do. This is closer to what you likely need.

int main()
{
    char (*lines)[500] = malloc(sizeof *lines);
    char *linetwo[4] = { malloc(500) }; // other three pointers will be NULL

    getline(*lines, sizeof *lines);
    getline(*linetwo, 500); // or linetwo[0]

    printf("%s", *lines);
    system("PAUSE");

    free(lines);
    free(linetwo[0]);
    return 0;    
}

Note: no error checking performed above. Use at your own discretion. Also note your getline may-well conflict with the POSIX library function getline , which is a different issue entirely.

char * lines[10]; 

Declares and allocates an array of pointers to char . Each element must be dereferenced individually.

char (* lines)[10]; /* invalid until assigned or malloc'ed) */ 

Declares (without allocating) a pointer to an array of char ('s). The pointer to the array must be dereferenced to access the value of each element.

To pass array of pointers in the function just pass the array name without using '*'

and that changes your function declaration with

void getline(char *line[], int lim)

and calling with

getline(linetwo, 500);

This is the easiest way to do so

void getline(char *line, int lim)

This function expects a pointer.

You are passing array of pointer to it ( *linetwo[4] ) .Thus give an error.

To pass *linetwo[4] to pass this you can do this

void getline(char **line, int lim)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM