Reputation: 376
I have a problem with a character array in my c program.
The program immediately shutdown when I run it. I think the problem is somewhere with passing the character array in the function.
here's my code:
#include<stdio.h>
#include<string.h>
#define DAGEN 7
void inlezen(int[][DAGEN], char[][12]);
int main(void)
{
int i;
int temp[1][DAGEN];
char dagen[7][12];
strcpy(dagen[0], "MA");
strcpy(dagen[1], "DI");
strcpy(dagen[2], "WOE");
strcpy(dagen[3], "DO");
strcpy(dagen[4], "VR");
strcpy(dagen[5], "ZA");
strcpy(dagen[6], "ZO");
inlezen(temp, 1, DAGEN, dagen, 7, 12);
}
void inlezen(int t[][DAGEN], char d[][12])
{
int i;
for (i = 0; i < DAGEN; i++)
{
printf("Geef de temperatuur overdag van %s", d[i]);
scanf("%d%*c", &t[0][i]);
}
for (i = 0; i < DAGEN; i++)
{
printf("Geef de temperatuur 's avonds van %s", d[i]);
scanf("%d%*c", &t[1][i]);
}
}
I've edited my code, but it still doesn't work.
Upvotes: 0
Views: 80
Reputation: 134286
In your code
strcpy(dagen[6], "ZO");
you're accessing out of bound memory by using 6 as the index value. Your definition of dagen
char dagen[6][12];
only permits a valid access up to 5 as the first index. ] By using 6, it invokes undefined behaviour.
FWIW, C uses 0
based indexing for arrays.
That said, the call
inlezen(temp, 1, DAGEN, dagen, 6, 12);
does not match the function signature, at all.
Finally, scanf()
family expects a pointer to variable type of arguments for supplied format specifiers, so, the
scanf("%d%*c", t[0][i]);
statements should be actually
scanf("%d%*c", &t[0][i]);
and likewise.
Upvotes: 3
Reputation: 16607
void inlezen(int[][DAGEN], char[][12]);
See this prototype you declared
and what values you pass to it -inlezen(temp, 1, DAGEN, dagen, 6, 12);
in main
.
And this strcpy(dagen[6], "ZO");
.Declaration of array was char dagen[6][12];
so index can go from 0
to 5
.You access out of bound memory ,thus invokes UB.Either remove this line or increase size to char dagen[7][12];
These statements -
scanf("%d%*c", t[0][i]);
.....
scanf("%d%*c", t[1][i]);
should be -
scanf("%d",&t[0][i]);
.....
scanf("%d",&t[1][i]);
Upvotes: 1