consider the code and its result:
while ((row = mysql_fetch_row (table_info)) != NULL)
{
answer='\0';
printf ( "%s: ", row[0] );
scanf ( "%c", &answer );
getchar();
if ( answer == 'y')
{
printf ( "*****\n" );
table_name[index] = malloc ( strlen(row[0]) + 1 );
printf ( "*****\n" );
memcpy ( &table_name[index], &row[0], strlen(row[0]) + 1 );
}
printf ( "finally inserted: %s \n", table_name[index]);
}
The result on execution:
1_time_access: y
*****
*****
finally inserted: 1_time_access
2_time_access: y
*****
*****
finally inserted: 2_time_access
39_time_access: y
*****
*****
finally inserted: 39_time_access
Explanation of result: row[0] has value 1_time_access, 2_time_access, 39_time_access. Now Consider a better way of doing it which is using a format string to escape the \n. I run the following code but it gives segentation fault, I cannot understand why.
Code:
while ((row = mysql_fetch_row (table_info)) != NULL)
{
answer='\0';
printf ( "%s: ", row[0] );
scanf ( "%[^\n]%*c", &answer );
if ( answer == 'y')
{
printf ( "*****\n" );
fflush(stdout);
table_name[index] = malloc ( strlen(row[0]) + 1 );
printf ( "*****\n" );
fflush(stdout);
memcpy ( &table_name[index], &row[0], strlen(row[0]) + 1 );
}
printf ( "finally inserted: %s \n", table_name[index]);
fflush(stdout);
}
Result:
1_time_access: y
*****
./set-env.sh: line 17: 15263 Segmentation fault (core dumped) ./exec dataset_one
(do not worry about set-env.sh, it is the script running th program.)
I canot understand why this is happening.