Infracción de acceso al llenar la matriz char*
Frecuentes
Visto 663 veces
0
I've written a code in c:
const char *str[125000];
float k[125000];
long n;
char string[20];
int i;
scanf("%d",&n);
for (i=0;i<n;i++)
{
scanf("%s%f",&string,&k[i]);
p=p/k[i];
str[i]=_strdup(string);
}
At this point everything's perfect. The array gets filled even if the n=100000; However if I change
for (i=0;i<n;i++)
a
for (i=n;i>0;i--)
i get the "Access violation" error. I've got no idea why is this happening so I'm asking for your help. Thanks in advance.
2 Respuestas
3
Arrays in C the size of n go from 0 to n - 1. So your loop should be
for (i=n-1;i>=0;i--)
You get an error because you are trying to access memory out of bounds of that array.
Respondido el 09 de Septiembre de 13 a las 21:09
Wow, it did work. Thanks a lot. But I still don't get it. Even if the loop goes from n to 1, why would that matter, considering that the array's size is 125000 and n<=100000? - DannyPhantom
@DannyPhantom I don't know what was your test code, show the sscce. - este
1 vsync 10
that's the simplest test code which was failing. - DannyPhantom
No se que es eso 1 vsync 10
medio. - este
@DannyPhantom I just noticed that const char *str[125000];
y scanf("%s%f",&string
no funcionará. - este
2
When reading a character string using %s
you should not pass the address of the string, instead simply pass the string: scanf("%s%f",string,&k[i]);
.
Respondido el 09 de Septiembre de 13 a las 21:09
@Chad I am not sure I understand your comment but the way OP reads the value of k[i] seems ok to me. - Ivailo Strandjev
@DannyPhantom this is only one of your errors it seems. Also take a look at this.'s answer - Ivailo Strandjev
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas c access-violation or haz tu propia pregunta.
This is like one line different than your last question: stackoverflow.com/questions/18676383/… - dcaswell