I want to preface my question by mentioning that I am a CS student that is very new to coding.
I am attempting to write a script that will add a set of array of characters to two arrays that are nested within a loop. The array of characters are prefixes for two courses, and I am using a function called "matcher" (that accepts an array that will hold a prefix, and an integer that holds the course number that we want to match to the corresponding prefix) within the loop.
The issue that I am facing is that when I run this, the first array(.prefix3) gets concatenated with the prefix for the second array(.prefix4), which seems to happen after the loop runs for a second time. I am unsure as to why this is occurring, specially since each array can only hold 7 characters. Here is the code, thank you all in advance:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char name[20];
int ID;
int number_of_courses;
int course_numbers[4];
char prefix1[7];
char prefix2[7];
char prefix3[7];
char prefix4[7];
int taken;
} student_info;
void matcher(char *,int );
int main()
{
student_info students[100];
int j=2;
int course_placeholder;
for(int i=0;i<2;i )
{
printf("Enter course number %d:",i 1);//Type "9696" or "1232"
scanf("%d",&course_placeholder);
if(j==1)
{
matcher(students[0].prefix2,course_placeholder);
}
else if(j==2)
{
matcher(students[0].prefix3,course_placeholder);//this is concatenating the string for some reason. Trying to determine why.
}
else if(j==3)
{
matcher(students[0].prefix4,course_placeholder);
}
j ;
}
printf("%s\n%s\n",students[0].prefix3,students[0].prefix4);//students[0].prefix3 is concatenating for an unknown reason.
return 0;
}
void matcher(char *prefix_placeholder,int course_placeholder)
{
if(course_placeholder==9696)
{
strcpy(prefix_placeholder,"MAT 236");
}
else if(course_placeholder==1232)
{
strcpy(prefix_placeholder,"COP 220");
}
}
CodePudding user response:
The arrays
char prefix1[7];
char prefix2[7];
char prefix3[7];
char prefix4[7];
are too short to store 7-character strings like "MAT 236"
and "COP 220"
because they require at least 8-character arrays including terminating null-characters.
Allocate enough elements to avoid troubles.
CodePudding user response:
Although you cannot see it, string literals with 7 visible characters, such as this one:
"COP 220"
^ - NULL terminator is implied here
actually contain 8 characters, not 7. The last character is \0
( AKA NULL
)
So, when allocating memory in an array which is designed to contains C strings ( defined as a NULL
terminated char
array ) always include space enough for the NULL
char prefix1[8] = {0}; //1 extra element for NULL, all elements initialized to NULL
To test this yourself, do this:
size_t size = sizeof "MAT 236" ;//expect size == 8