Thread: Dynamic memory allocation example

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    If you want to initialize a bunch of elements of dynamically allocated array you can do as @Zeus_ told you:
    Code:
    p[0] = 5;
    p[1] = 15;
    p[2] = 5;
    p[3] = 53;
    p[4] = 101;

    Or, in C (not C++), with a compiler capable of compiling code compliant to ISO 9989:2011 standard (I am not sure, right now, but I believe ISO 9989:1999 already had compound literals), you can use compound literals, as in:
    Code:
    int *p = malloc( 5 * sizeof( int ) );
    memcpy( p, (int []){ 5, 15, 5, 53, 101 }, 5 * sizeof( int ) );
    Notice is easier to just simply do:
    Code:
     int a[] = { 5, 15, 5, 53, 101 };
    But you are asking how to inicialize a dynamic allocated buffer!
    Last edited by flp1969; 11-05-2019 at 12:53 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to add dynamic memory allocation
    By JJ57663 in forum C Programming
    Replies: 1
    Last Post: 04-26-2019, 07:07 PM
  2. dynamic memory allocation
    By abhi143 in forum C Programming
    Replies: 12
    Last Post: 10-09-2018, 07:22 AM
  3. C dynamic memory allocation
    By Romyo2 in forum C Programming
    Replies: 4
    Last Post: 06-03-2015, 07:04 AM
  4. Dynamic memory allocation
    By Luciferek in forum C++ Programming
    Replies: 118
    Last Post: 10-02-2008, 11:34 AM
  5. Dynamic memory allocation
    By amdeffen in forum C++ Programming
    Replies: 21
    Last Post: 04-29-2004, 08:09 PM

Tags for this Thread