Home > Software design >  Print the string using dynamically memory allocated
Print the string using dynamically memory allocated

Time:07-18

Hello, my question is: How to print out string 1 and string 2, not only string 2. I am new to dynamically memory allocated. My sample code is below, thanks for your help.

Result expected:

Hello

My name is Ken

enter image description here

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

int main(){
    int n, i;
    char *ptr;
    
    printf("How many strings you want to display?: ");
    scanf("%d", &n);
    
    ptr = (char*)malloc(n * sizeof(n));
    
    if(ptr == NULL){
        printf("Failed to allocate the memory to string!\n");
        exit(0);
    }
    
    for(i = 0; i < n; i  ){
        printf("String %d: ", i   1);
        fflush(stdin);
        scanf("%[^\n]", ptr);
    }
    
    printf("\n");
    printf("Strings you entered:\n");
    for(i = 0; i < n; i  ){
        printf("%s\n", ptr);
    }
}

CodePudding user response:

Please check the below code. I have marked modified lines with a comment starting with // CHANGE.

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

// CHANGE - free memory when not needed
void free_memory(char** ptr, int n)
{
    if (ptr)
    {
        int i;
        for (i = 0; i < n; i  )
        {
            if (ptr[i])
            {
                free(ptr[i]);
            }
        }
        free(ptr);
    }
}

int main(){
    int n, i;
    char **ptr; // CHANGE - make a double pointer - array of strings (imagine rows and columns)
    
    printf("How many strings you want to display?: ");
    scanf("%d", &n);
    
    
    ptr = (char**) malloc(n * sizeof(char*));    // CHANGE - allocate memory based on no. of rows (columns are string characters)
    
    if (ptr == NULL) {
        printf("Failed to allocate the memory to string!\n");
        exit(1);
    }
    
    getchar();  // CHANGE - read the newline character else fgets doesn't work
    for (i = 0; i < n; i  ) {
        ptr[i] = (char*) malloc(256 * sizeof(char)); // CHANGE - allocate memory for each row
        
        printf("String %d: ", i   1);
        if ( fgets(ptr[i], 256 * sizeof(char), stdin) == NULL ) {
            printf("Failed to get line input\n");
            free_memory(ptr, n);
            exit(1);
        }
        ptr[i][strlen(ptr[i]) - 1] = '\0';  // CHANGE - remove extra newline character at the end
    }
    
    printf("\n");
    printf("Strings you entered:\n");
    for (i = 0; i < n; i  ) {
        printf("%s\n", ptr[i]); // CHANGE - print each row
    }
    free_memory(ptr, n);
    return 0;
}

CodePudding user response:

First, there are two numbers that should be decided:

  1. the number of strings the user wants to input and
  2. the length of the strings (or the lengths of each string).

Each string will be stored in a char*. And all strings together will be stored in a char**. The length of char** will be your n in this case. And length of each char* can be decided however you want. I prefer to use a directive #define to define a constant like 100. You can also do a global or local variable or just a digit. Also don't forget to free anything you allocate. Check below for details. And happy coding!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_STRING_SIZE 100

int main(){
    int n, i;
    // stores all the strings
    char **ptr;
    
    printf("How many strings you want to display?: ");
    scanf("%d", &n);
    
    // allocate memory of size (n * size of char*)
    ptr = (char**)malloc(n * sizeof(char*));
    if(ptr == NULL){
        printf("Failed to allocate the memory to string!\n");
        exit(-1);
    }

    // for each pointer, allocate memory of size (MAX_STRING_SIZE * size of char)
    for(i = 0; i < n; i  )
        // I'm too lazy to put validity check here but you got the idea...
        ptr[i] = (char*)malloc(MAX_STRING_SIZE * sizeof(char));
    
    
    for(i = 0; i < n; i  ){
        printf("String %d: ", i   1);
        fflush(stdin);
        scanf("%[^\n]", ptr[i]);        // use ptr[i]
    }
    
    printf("\n");
    printf("Strings you entered:\n");
    for(i = 0; i < n; i  ){
        printf("%s\n", ptr[i]);         // use ptr[i]
    }

    // free all of them
    for(i = 0; i < n; i  )
        free(ptr[i]);
    free(ptr);

    return 0;
}
  • Related