(Sorry if duplicate, couldn't find a simple answer to this question) Learning how to form structures and having buffer warnings when using strcpy. I'm thinking I need to malloc to create buffer space? I thought defining the array did that. I added +1 to the strcpy length to accommodate the string term /0... but still getting warnings. Your help is greatly appreciated...
CODE:
#include <string.h>
#include <stdio.h>
char id[9] = "123456789";
char fn[20] = "firstname";
char ln[20] = "lastname";
char bd[10] = "99/99/1900";
int h = 72;
int w = 215;
typedef struct PERSON {
char ID[9];
char firstName[20];
char lastName[20];
char birthDate[10];
int height;
int weight;
int BMI;
}PERSON;
int main() {
PERSON p1;
strcpy_s(p1.ID, 10, id);
strcpy_s(p1.firstName, 21, fn);
strcpy_s(p1.lastName, 21, ln);
strcpy_s(p1.birthDate, 11, bd);
p1.height = h;
p1.weight = w;
p1.BMI = (p1.weight / (p1.height * p1.height) * 703);
printf("ID: %s\nFirst Name: %s\nLast Name: %s\nBirth Date: %s\nHeight: %d\nWeight: %d\nBMI: %d\n", p1.ID, p1.firstName, p1.lastName, p1.birthDate, p1.height, p1.weight, p1.BMI);
return 0;
}
Output: I'm getting firstname showing up on the ID line, telling me I'm having some memory issues?
ID: 123456789firstname
First Name: firstname
Last Name: lastname
Birth Date: 99/99/1900
Height: 72
Weight: 215
BMI: 0
C:\Users\.................ep.exe (process 56868) exited with code 0.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .
If I change this:
strcpy_s(p1.ID, 10, id);
to:
strcpy_s(p1.ID, 9, id);
the code doesn't complile. I get a Debug Assertion Failed. Buffer is too small. reinforcing my thoughts on memory issues.
Not too familiar with malloc. will I need to malloc all arrays within the struct? Thanks for the help!!