user3344960
user3344960

Reputation: 9

Why char variable in struct need to set as pointer variable only work?

struct telephone
{
    char *name;
    int number;
};

int main()
{
    struct telephone index;
    index.name = "Jane Doe";
    index.number = 12345;
    printf("Name: %s\n", index.name);
    printf("Telephone number: %d\n", index.number);

    return 0;
}

Can i know why char type need a pointer only can work, but int no need?

Upvotes: 0

Views: 81

Answers (4)

herohuyongtao
herohuyongtao

Reputation: 50667

Sure you can put a char in a struct. Of course, in this case, it is only a char, not a pointer to char (i.e. string in C).

For example:

struct telephone
{
    char name;                            // a char
    int number;
};

int main()
{
    struct telephone index;
    index.name = 'a';                    // assign a char
    index.number = 12345;
    printf("Name: %c\n", index.name);    // print a char
    printf("Telephone number: %d\n", index.number);

    return 0;
}

Upvotes: 0

pizzaEatingGuy
pizzaEatingGuy

Reputation: 888

You can you just char too. But it will be just a single character. char* is a string (think of it like array of chars) like int* is like a array of int.

the pointer points to the first character of the string.

Upvotes: 0

Evan Carslake
Evan Carslake

Reputation: 2359

The character needs to be a pointer because it is being used as a "string." That is what a string declaration looks like in C. The pointer points to the first character in the string. Adding +1 to the pointer will give you the next character in the C-String.

Upvotes: 0

A.E. Drew
A.E. Drew

Reputation: 2137

You only need a char* if that is what you want. Here name points to a sequence of char. If you want your struct to contain a single char than you can do so.

Upvotes: 1

Related Questions