I am trying to solve a problem on a competitive programming page, and it had occurred to me that a good way to solve it would be by making a dynamic array, right now I don't care about the problem and what I want to know is how something like this could be implemented.
The idea is first they give us the number of cases (the size of the array) and then we make certain tours of that array, I would also have to apply it to a matrix of characters (an array of strings), this code that I have here works well when the input of cases is 1 <n <110, but of course, when that range is passed (it should be up to 300000 ) gives me a memory access error Process finished with exit code -1073741819 (0xC0000005)
, which is normal considering what I'm trying to do, I don't even know if it can, thank you very much in advance!
This is my code:
int main() {
int cases, i, j, max = 0;
while ((scanf("%d", &cases)) != EOF) {
int *victims;
victims = (int *) malloc(cases * sizeof(int));
const char **date;
date = (const char **) malloc(cases * sizeof(char));
for (i = 0; i < cases; i++) {
date[i] = (char *) malloc(10 * sizeof(char));//String max length is 10.
}
for (i = 0; i < cases; i++) {
scanf("%s", date[i]);
scanf("%d", &victims[i]);
}
}
}
The lines
const char **date;
date = (const char **) malloc(cases * sizeof(char));
are wrong. The element is const char*
, so you have to allocate for that.
In other words, you have to allocate size of a pointer, not size of a char, for each elements.
Moreover, the objects pointed at by the elements of the array date
will be modified via scanf()
later, so they should be char*
, not const char*
.
it should be
char **date;
date = malloc(cases * sizeof(char*));
or
char **date;
date = malloc(cases * sizeof(*date));
Also the line
date[i] = (char *) malloc(10 * sizeof(char));//String max length is 10.
is wrong. You have to allocate one more element for the terminating null-character to allow 10-character strings to be stored there.
It should be:
date[i] = malloc(11 * sizeof(char));//String max length is 10.
Also note that:
sizeof(char)
because it is defined to be 1.malloc()
is considered as a bad practice.User contributions licensed under CC BY-SA 3.0