0
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?

  • the `char *name` is an array of chars ;) – demonking Feb 26 '14 at 17:49
  • @demonking - not an *array* rather a pointer to type `char`. String literals are exceptions when using pointer assignments in the case of `char` type. But one needs to be careful and make sure if the string is dynamic, then the pointer to `char` must be allocated using `malloc` family of memory allocation functions or even `strdup`. **READ** this [answer](http://stackoverflow.com/a/2245983/206367) that explains why! – t0mm13b Feb 26 '14 at 17:51
  • @demonking char[] name is an array of char. char* name is a pointer to a char. – Fabian Bigler Feb 26 '14 at 18:02

4 Answers4

1

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.

A.E. Drew
  • 2,097
  • 1
  • 16
  • 24
0

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;
}
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
0

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.

Evan Carslake
  • 2,267
  • 15
  • 38
  • 56
0

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.

pizzaEatingGuy
  • 878
  • 3
  • 10
  • 19