- #1
doktorwho
- 181
- 6
I was supposed to write a program that has a while loop in which two people, person1 and person2 input a string. The program runs the loop until one of the people inputs "it's over". At that time the program should exit and print out the correspodance between these two people while they were in a loop.(Formatted so that you can see what they wrote and not all combined together). For that it should use a dynamically aloocated array of strings (something like char **corr, using double pointers)
Below is the code without the memorization of the correspondance.
I've never used ** pointer before but know that its an array of pointers. Do i now create two ** char elements to hold the conversation for each and how would i print them? How would i know when the other one finished his sentence? Do pointers in an array of pointers (char **some_name) point to strings or chars?
Below is the code without the memorization of the correspondance.
C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int counter = 0;
while (1) {
char *person1, *person2, c;
int i = 0;
person1 = (char*)calloc(500, sizeof(char));
person2 = (char*)calloc(500, sizeof(char));
printf("The person1 says: \n");
while ( (c = getchar()) != '\n') {
person1[i++] = c;
}
person1[i] = '\0';
i = 0;
printf("The person2 says: \n");
while ( (c= getchar()) != '\n') {
person2[i++] = c;
}
person2[i] = '\0';
person1 = realloc(person1, (strlen(person1)+1)*sizeof(char)); //Freeing up unused space
person2 = realloc(person2, (strlen(person2)+1)*sizeof(char));
if (strcmp(person1, "it's over") == 0) {
printf("The ending. The program will exit. \n");
system("pause");
break;
}
if (strcmp(person2, "it's over") == 0) {
printf("The ending. The program will exit. \n");
system("pause");
break;
}
free(person1);
free(person2);
counter += 1;
}
printf("%d", counter); \\number of times each of them sent a message.
}