linguae wrote:
Hello. In my C program, I have an array of character pointers. I'm
trying to input character strings to each index of the character
pointer array using scanf(), but when I run the program, I get
segmentation faults and core dumps. The problem occurs when the
program calls scanf(). I don't know what is wrong with it.
Here is my code:
#include "stdio.h"
#define SIZE 5
void input(char *string, char *string2);
int main(void)
{
char *string[SIZE], *string2[SIZE];
int counter;
for(counter = 0; counter <= SIZE - 1; counter++)
input(string[counter], string2[counter]);
putchar('\n');
for(counter = 0; counter <= SIZE - 1; counter++)
printf("%s %s\n", string[counter], string2[counter]);
return 0;
}
void input(char *string, char *string2)
{
printf("Enter string 1: ");
scanf("%s", string);
printf("Enter string 2: ");
scanf("%s", string2);
}
This is just the sort of thing where my ggets routine will be
handy. See:
<http://cbfalconer.home.att.net/download/ggets.zip>
and rewrite your program more or less as follows (untested)
#include <stdio.h>
#include "ggets.h"
#define SIZE 5
void input(char **str_1, char **str_2)
{
printf("Enter string 1: "); fflush(stdout);
if (0 != ggets(str_1)) puts("error");
printf("Enter string 2: "); fflush(stdout);
if (0 != ggets(str_2)) puts("error");
}
int main(void)
{
char *string[SIZE], *string2[SIZE];
int counter;
for (counter = 0; counter <= SIZE - 1; counter++)
input(&string[counter], &string2[counter]);
putchar('\n');
for (counter = 0; counter <= SIZE - 1; counter++)
printf("%s %s\n", string[counter], string2[counter]);
return 0;
}
Note the ampersands in the calls to input. BTW the exit conditions
in the for loop are more conventionally written as "counter <
SIZE".
After all that ggets will handle securing memory for your strings,
lack of which is the fundamental problem in your code.
--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson