Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,943 questions

51,884 answers

573 users

How to copy existing struct to new allocated struct in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

enum { buffer_size = 32 };

struct buffer {
    size_t id;
    char bufferX[buffer_size];
};

int main(void) {
    struct buffer buf;
    
    buf.id = 5893;
    strcpy(buf.bufferX, "c programming");
    printf("buf.id: %d : buf.bufferX: %s\n", buf.id, buf.bufferX);

    struct buffer *p = (struct buffer *)malloc(sizeof(struct buffer));
 
    if (p == NULL) {
        puts("Malloc error");
        exit(1);
    }
 
    memcpy(p, &buf, sizeof(struct buffer));
    
    printf("p->id: %d : p->bufferX: %s", p->id, p->bufferX);
    
    free(p);
}





/*
compile:

buf.id: 5893 : buf.bufferX: c programming
p->id: 5893 : p->bufferX: c programming

*/

 



answered Apr 28, 2022 by avibootz

Related questions

2 answers 157 views
1 answer 98 views
1 answer 190 views
1 answer 183 views
1 answer 187 views
1 answer 264 views
264 views asked Jan 26, 2016 by avibootz
...