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,884 questions

51,810 answers

573 users

How to use array of pointers to dynamic allocate strings in C

1 Answer

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

#define ARRAYSIZE 3 
#define BUFFERSIZE 32 

int main(void)
{
    char buffer[BUFFERSIZE] = "";
    char* p[ARRAYSIZE] = { NULL }; 

    for (size_t i = 0; i < ARRAYSIZE; i++) {
        printf("Enter string %zu: ", i);
        scanf("%s", buffer);    
        p[i] = malloc((strlen(buffer) + 1) * sizeof(char)); 
        if (!p[i]) {
            puts("malloc error");
            return 1;
        }
        strcpy(p[i], buffer);              
    }

    for (size_t i = 0; i < ARRAYSIZE; i++) {
        puts(p[i]);
        free(p[i]);
    }

    return 0;
}


/*
run:

Enter string 0: c
Enter string 1: c++
Enter string 2: java
c
c++
java

*/

 



answered Feb 21, 2023 by avibootz

Related questions

1 answer 167 views
1 answer 173 views
1 answer 144 views
...