Hi everyone. I have a quick question regarding a 2d dynamic array, and how to print it.
Here is the code I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define merror() {printf("Memory allocation problem \n");exit(1);}
int main()
{
int i,j,k,z;
int size;
char buffer[21];
char buf[21];
char** p;
/* For entering the amount of names */
A: printf("How many names do you want to enter: ");
fflush(stdout);
for(i=0; i<20; i++) {
buffer[i]=fgetc(stdin);
if (buffer[i]=='\n') {
buffer[i]='\0';
break;
}
}
if (i==20) {
printf("Input too long!\n");
while(fgetc(stdin)!='\n');
goto A;
}
if (buffer[0]=='\0') {
printf("empty input\n");
goto A;
}
size = atoi(buffer);
printf("You will enter %d names\n", size);
p = (char**)malloc(size*sizeof(char*));
if (p == NULL) merror();
for (j=0; j<size; j++) {
p[j]=(char*)malloc(21);
if (p[j] == NULL) merror();
B: printf("Enter a name:");
fflush(stdout);
for(k=0; k<20; k++) {
buffer[k]=fgetc(stdin);
if (buffer[k]=='\n') {
buffer[k]='\0';
break;
}
}
if (k==20) {
printf("input too long\n");
while(fgetc(stdin)!='\n');
goto B;
}
if (buffer[0]=='\0') {
printf("Empty input. Please re-enter\n");
goto B;
}
}
// Here is where i need to print the output of words
// Not too sure how to do this i.e., what for statements, and how to strcpy from the buffer to array and print it
}
return 0;
}
Here is a quick example of what the program is supposed to do:
User inputs how many words he/she wants
It dynamically allocates it, and for the words they can not be longer than 20 chars (i.e. my malloc statement of 21)
Then, my problem, is taking those entered words, and printing them
Ex..
Enter how many words: 3
You will enter 3 words
Enter word: Bob
Enter word: Joe
Enter word: Bill
You entered
Bob
Joe
Bll
Any help is greatly appreciated