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]);
}
}