1

I am working with dynamic memory allocation and strings. The assignment is to prompt the user for the number of char strings they'll enter (max 80 char each), then have a function get the strings and another function print the strings and character counts.

I get the data to/from the functions using a pointer array. Everything worked great, and I was ready to submit the assignment, until I re-read the question and saw the pointer array has to be dynamically allocated also. I got that working, but now when i = 0, puts(strptr1[i]); just gives me gibberish (ɶ?). Meanwhile, i = 1 and up are fine.

Thank you, here is my code.

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

void inputStrings(char *strptr1[], int n);
void outputStrings(char *strptr1[], int n);

int main()
{
    int n = 0;
    char *strptr = 0;

    printf("This program uses dynamic storage to manipulate character strings. Fun!");

    printf("\n\nHow many strings will you enter? ");
    scanf("%d", &n);

    fseek(stdin,0,SEEK_END); // Clear input buffer

    // char *strptr[n];
    strptr = (char *) calloc(n, sizeof(char));

    inputStrings(strptr, n);

    outputStrings(strptr, n);

    return 0;
}

void inputStrings(char *strptr1[], int n) // Prompt for input and copy into dynamic memory
{
    const int STRLNG = 80;
    int i = 0;
    char strname[STRLNG];

    printf("Input strings:\n");

    for (i = 0; i < n; i++)
    {
        gets(strname);
        strptr1[i] = (char *) malloc(strlen(strname+1));
        strcpy(strptr1[i], strname);
    }
}

void outputStrings(char *strptr1[], int n) // Determine length and print length and string
{
    int i = 0;

    printf("\nChar | String\n");

    for (i = 0; i < n; i++)
    {
        printf(" %2d  | ", strlen(strptr1[i]));
        puts(strptr1[i]);
    }
}
iMPose27
  • 35
  • 5
  • `(char *) malloc(strlen(strname+1))` should be `malloc( strlen(strname) + 1 )` . Your ver does not allocate enough space. – M.M Jul 18 '14 at 02:10

2 Answers2

1

Since a C string is a pointer, you need a pointer to pointer to make a dynamic array:

char **strptr;
...
strptr = calloc(n, sizeof(char*));

This will allocate enough memory for the dynamic array of strings.

Do not forget to free all the memory that you have allocated! This includes both the array of strings, and the strings themselves:

for (i = 0; i < n; i++) {
    free(strptr[i]);
}
free(strptr);

Note: it is not necessary to cast the results of malloc or calloc in C.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Because the user presses enter after entering the number of strings, the newline is added to the input buffer. Add getchar(); before the for loop for entering strings.

Also, strptr is the wrong type. Declare it as a **char instead of just *char.

McLovin
  • 3,554
  • 1
  • 14
  • 15