I\'m having trouble dynamically allocating memory for an array. I\'ve been debugging for hours, any pointers?
I posted the rest of the code. It is simply supposed to exc
This code seems to work:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum { MAX_LINES = 50 };
static void printArray(char *inputs[], int rows);
static int readLine(char *buffer, size_t buflen);
int main(void)
{
int count = 0;
char *lines[MAX_LINES];
char tmp[50];
for (count = 0; count < MAX_LINES; count++)
{
if (readLine(tmp, sizeof(tmp)) == EOF)
break;
lines[count] = (char *) malloc((strlen(tmp)+1)* sizeof(char));
if (lines[count] == 0)
break;
strcpy(lines[count], tmp);
}
putchar('\n');
printArray(lines, count);
return(0);
}
static int read_line(char *buffer, size_t buflen)
{
printf("Enter string: ");
if (fgets(buffer, buflen, stdin) == 0 || strcmp("xx\n", buffer) == 0)
return EOF;
return 0;
}
static void printArray(char *inputs[], int rows)
{
for (int i = 0; i < rows; i++)
printf("%d: %s", i, inputs[i]);
}
Sample run 1 (using EOF):
$ ./rl
Enter string: Abyssinia
Enter string: Wimbledon Common
Enter string: ^D
0: Abyssinia
1: Wimbledon Common
$
Sample run 2 (using 'xx
'):
$ ./rl
Enter string: Abyssinia
Enter string: Wimbledon Common
Enter string: Strawberry Lemonade
Enter string: xx
0: Abyssinia
1: Wimbledon Common
2: Strawberry Lemonade
$
What's different? I fixed the type on tmp
as noted in a comment. I created a function readLine()
to manage the prompt and read and compare with "xx\n"
process to avoid repetition. I avoided using strdup()
but do check that malloc()
succeeds before using the pointer returned. I ensure that there are not too many lines read in (the for
loop). The printArray()
code only takes the number of rows because the strings are of varying length. I removed the exchange()
function since it was not being used and I couldn't see how it was supposed to be used. The code is complete and compilable (so it is an SSCCE — Short, Self-Contained, Correct Example).