C-Language flexible array (variable-length array) __c language

Source: Internet
Author: User

Variable arrays are already supported in C99, but not supported in VC, but flexible arrays (special variable-length arrays) are supported.

What is a flexible array, how to use it. Please look at the code below.

#include <stdio.h>
#include <string.h>
#include <malloc.h>
///Flexible array////
*
The last element in the C99 is allowed to be an array of unknown size, which is called a flexible array member, and the
flexible array member must precede at least one other member.
* *
typedef struct _FLEX_ARRAY
{
	int nlen;
	Char szbuff[];//flexible array member
} Flex_array,*pflex_array;

int main ()
{
	char szmsg[] = "This is a C programe.";

	Structure body size equals 4
	int stsize = sizeof (Pflex_array);//=sizeof (int)
	//allocating memory
	pflex_array Psta = (pflex_array) malloc (Stsize + 100*sizeof (char));
	
	Ordinary members and flexible array members in a structure are assigned
	Psta->nlen = strlen (szmsg);
	memcpy (psta->szbuff,szmsg,psta->nlen+1);
	
	Structure body size stsize still equals 4 Description: The flexible array is not actually a member of the structure body
	stsize = sizeof (PSTA);

	Freeing memory free
	(PSTA);

	return 0;
}


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.