Learn point C language (23): Data type

Source: Internet
Author: User
Tags printf

C Language memory allocation is simple: malloc, calloc, realloc, free

malloc (number of bytes); Returns the first address of the memory segment, void.

Calloc (number, type size); The difference with malloc is that it initializes the memory to be empty.

ReAlloc (original pointer, number of bytes); Reallocation of memory allocated by malloc, calloc; There are too many things to note here:

1, if reduced, will cut off a piece, will retain the previous content;

2, if expanded, will still retain existing content, but the new memory will not initialize;

3, in the expansion, it is possible that the memory address will change, so that the original pointer will be discarded, but the return value is a new pointer, so continue to use should be the return value.

If the allocation fails, it returns NULL, typically because of insufficient memory; Allocating 0 bytes of memory also returns NULL but that doesn't make sense.

They are all freed with free (pointers).

1. Allocate memory to an integer:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  int *p = NULL;

//  p = malloc(sizeof(int)); /* 应该像下一句同时类型转换, 不然在 C++ 里面不行 */
  p = (int *)malloc(sizeof(int));

  *p = 100;
  printf("%d\n", *p);

  free(p);

  getchar();
  return 0;
}

2. Allocate memory to 3 integers:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  int *p = NULL;

  p = (int *)malloc(sizeof(int)*3);

  *p = 111;
  *(p+1) = 222;
  *(p+2) = 333;

  printf("%d,%d,%d\n", *p, *(p+1), *(p+2));

  free(p);
  getchar();
  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.