如何纠正 c 中的访问冲突错误?
当我运行该代码时,出现“访问冲突写入位置”错误。我知道这可能是因为我正在尝试更改 const 值,但我不知道代码的正确性。
OBS:我想创建 n 个数组来存储 25 个字符的字符串。
#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]);
}
错误: BEE-URI 1022.exe 中的 0x00007FFBC6EC916F (ucrtbased.dll) 引发异常:0xC0000005:写入位置 0xFFFFFFFFFFFFFFCD 时发生访问冲突。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此调用的第一个参数表达式应具有类型
char *
,因此您至少需要编写
而不是 且使用的转换说明符
也不正确。使用
或
注意,目前尚不清楚您要使用此 for 循环实现什么目标,
也许您的意思类似于以下内容
The first argument expression of this call shall have the type
char *
, So instead ofyou need at least to write
And the used conversion specifier
is also incorrect. Either use
or
Pay attention to that it is unclear what you are trying to achieve using this for loop
Maybe you mean something like the following
您说您想要
n
个数组,每个数组包含 25 个字符,但您malloc
是一个包含n * 25
字符的数组。我认为您想要这样的东西:请注意,您还应该检查
malloc
调用的返回值,以便知道它们是成功还是失败。与fgets
和scanf
相同。顺便说一句,请记住,25 个字符的字符串只能容纳 24 个字符,因为必须为终止空字符留有空间。
You say you want
n
arrays of 25 characters each, but what youmalloc
is one array ofn * 25
characters. I think you want something like this:Note that you should also check the return values from your
malloc
calls so you know if they succeeded or failed. Same withfgets
andscanf
.BTW, remember that a string of 25 characters can only hold 24 characters because you must have room for the terminating null character.