I´m getting a "Access violation writing location" error when I run that code. I know that probably is because I´m trying change a const value, but I dont know how correct the code.
OBS: I want create n arrays to storage strings with 25 characters.
#include <stdio.h>
#include <stdlib.h>
int main() {
//variables
int i = 0, n = 0;
//code
scanf("%d\n", &n); //define the number of arrays
char* exp;
exp = (char*)malloc(n * 25); //allocate memory for the string size
for (i = 0; i < n; i )
{
//takes strings from keyboard
fgets(exp[i], n*25, stdin); //the below error takes place here.
}
//prints the first string taked from stdin
printf("%s", exp[0]);
}
ERROR: Exception thrown at 0x00007FFBC6EC916F (ucrtbased.dll) in BEE-URI 1022.exe: 0xC0000005: Access violation writing location 0xFFFFFFFFFFFFFFCD.
CodePudding user response:
The first argument expression of this call shall have the type char *
, So instead of
fgets(exp[i], n*25, stdin);
you need at least to write
fgets(exp, n*25, stdin);
And the used conversion specifier
printf("%s", exp[0]);
is also incorrect. Either use
printf("%c", exp[0]);
or
printf("%s", exp);
Pay attention to that it is unclear what you are trying to achieve using this for loop
for (i = 0; i < n; i )
{
fgets(exp, n*25, stdin); //the below error takes place here.
}
Maybe you mean something like the following
char ( *exp )[25];
exp = malloc( n * sizeof( char[25] ) );
for (i = 0; i < n; i )
{
fgets(exp[i], sizeof( exp[i] ), stdin);
}
// either
// printf( "%s", exp[0] );
// or the loop below
for (i = 0; i < n; i )
{
printf( "%s", exp[i] );
}
free( exp );
CodePudding user response:
You say you want n
arrays of 25 characters each, but what you malloc
is one array of n * 25
characters. I think you want something like this:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n;
char **exp;
scanf("%d", &n); // get the number of arrays
exp = malloc(n * sizeof *exp); // allocate memory for n string pointers
for (int i = 0; i < n; i )
exp[i] = malloc(25 * sizeof **exp);
for (int i = 0; i < n; i )
fgets(exp[i], 25, stdin); // takes strings from keyboard
printf("%s", exp[0]); // print 1st string taken from stdin
}
Note that you should also check the return values from your malloc
calls so you know if they succeeded or failed. Same with fgets
and scanf
.
BTW, remember that a string of 25 characters can only hold 24 characters because you must have room for the terminating null character.