Using character pointers in C structure

Source: Internet
Author: User
Tags printf

The following example defines two structures, and because of the existence of strings in the member, the struct uses a character array, while struct two uses a character pointer.

#include <stdio.h>
#define LEN 20
struct info {
    char first[LEN];
    char last[LEN];
    int age;
};
struct pinfo {
    char * first;
    char * last;
    int age;
};
int main()
{
    struct info one = {"Opw", "Cde", 22};
    struct pinfo two = {"Tydu", "Gqa", 33};
    printf("%s %s is %d years old.\n", one.first, one.last, one.age);
    printf("%s %s is %d years old.\n", two.first, two.last, two.age);
    return 0;
}

The code works fine. But for struct pinfo variable two, there are hidden dangers. Because two strings in the two are stored in the literal constant area. And the structure of the store is only two addresses.

printf("one.first's size: %d\n",sizeof(one.first));
printf("two.first's size: %d\n",sizeof(two.first));

Results:

one.first's size: 20
two.first's size: 4

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.