Slaine
Slaine

Reputation: 13

how do I input values into a structure using pointers?

I have a small problem with this program I'm writing, I'm trying to input data into a structure using a pointer but the compiler just gives me an error stating: "dereferencing pointer to incomplete type"

the function of the program is simple: a program that uses functions to input data into a structure using pointers

heres the code: the main function simply calls the input function and passes the structure pointer as an argument

void input(struct test *ptr)
{
printf("Enter: \n");
fflush(stdin);
scanf("%s",&ptr->entry);

}

void print(struct test *ptr)
{

}

int main()
{
    int counter;
    struct test
    {
        char entry[20];

    }p[4];
    struct test *ptr=p;
    ptr=&p;

    for(counter=0;counter<=4;counter++)
        {
            input(ptr);
            ptr++;
        }
    return 1;
}

The print function is still empty.

Upvotes: 0

Views: 8416

Answers (2)

The Archetypal Paul
The Archetypal Paul

Reputation: 41769

First problem is that struct test is defined only inside your "main" function and is not accessible to input or print. Define it outside all the functions.

Then you want to scan a string, not a character, so you need "%s". Actually "%19s" so if the input is too long you don't walk off the end of the entry array (Hat tip to @BLUEPIXY)

And ptr->entry is the address of where you want to put the string so you don't need &ptr->entry but ptr->entry

You assign to ptr twice in main. The second is wrong (again, p is the address of the array of structs, so you have it right in the initialisation. The assignment of &p is wrong.

Finally, your for-loop executes 5 times (0,1,2,3,4) and the last iteration accesses one off the end of your 4-element p array

Putting that altogether:

#include <stdio.h>

struct test
{
    char entry[20];
};

void input(struct test *ptr)
{
    printf("Enter: \n");
    fflush(stdin);
    scanf("%19s", ptr->entry);
}

void print(struct test *ptr)
{

}

int main()
{
    int counter;
    struct test p[4];
    struct test *ptr=p;

    for(counter=0;counter<4;counter++)
    {
        input(ptr);
        ptr++;
    }
    return 1;
}

Upvotes: 1

Gopi
Gopi

Reputation: 19874

Scanning a string using & is not required. A string should be scanned using %s not %c. Filling your empty print. Preferably change your function name print to something else.

Check the below code:

#include <stdio.h>
#include <string.h>
    struct test
    {
        char entry[20];

    }p[4];

void input(struct test *ptr)
{
printf("Enter: \n");
scanf("%s",ptr->entry);
return;
}

void print(struct test *ptr)
{
int i;
for(i=0;i<4;i++)
{
    printf("%s\n",ptr[i].entry);
}
return;
}
int main()
{
    int counter;

    struct test *ptr=p;

    for(counter=0;counter<4;counter++)
        {
            input(ptr);
            ptr++;
        }
        print(p);
    return 0;
}

Upvotes: 0

Related Questions