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.

40,026 questions

51,982 answers

573 users

How to allocate string in C

2 Answers

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

char* alocate_string(char* str, int size) {
    str = (char*)malloc(size * sizeof(char)); 

    if (str == NULL) {
        printf("Memory allocation failed\n");
    }

    return str;
}

int main(void) {

    char* str = NULL;
        
    str = alocate_string(str, 64);

    if (str != NULL) {
        strcpy(str, "c programming");
        printf("%s", str);
        free(str);
    }

    return 0;
}




/*
run:

c programming

*/

 



answered Nov 30, 2023 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void alocate_string(char** str, int size) {
    *str = (char*)malloc(size * sizeof(char)); 

    if (str == NULL) {
        printf("Memory allocation failed\n");
    }
}

int main(void) {

    char* str = NULL;
        
    alocate_string(&str, 64);

    if (str != NULL) {
        strcpy(str, "c programming");
        printf("%s", str);
        free(str);
    }

    return 0;
}




/*
run:

c programming

*/

 



answered Nov 30, 2023 by avibootz
edited Nov 30, 2023 by avibootz

Related questions

1 answer 81 views
1 answer 79 views
79 views asked Nov 30, 2023 by avibootz
1 answer 191 views
2 answers 260 views
2 answers 193 views
193 views asked Jul 10, 2015 by avibootz
1 answer 191 views
191 views asked May 19, 2025 by avibootz
...