Copying a C-string into an array in a structure

Greetings all,

I'm able to do the exercise below using std::string, but I can't get it to work using the pointer-to-char, as intended by the author.
I tried using strncpy in the set_structure function, but I get the following error message: "This function or variable may be unsafe". When I use strncpy_s the programme displays only 4 first characters of the structure name member.
My questions are:
1) Why is it displaying only those first 4 characters?
2) What am I doing wrong? How can I get it to work with the full names?
3) Am I right to assume that I can use a C-string as a default argument, as I have done here?
4) Any advice on how to make the code better? Are there any things that I have done that could have obviously been done in a better/simpler way?

Thank you for your help.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*The CandyBar structure contains three members. The first member holds the brand name of a candy bar.
The second member holds the weight (which may have a fractional part) of the candy bar, and the third member holds the number of calories (an integer value) in the candy bar. Write a program that uses a function that takes as arguments a reference to CandyBar, a pointer-to-char, a double, and an int and uses the last
three values to set the corresponding members of the structure. The last three arguments should have default values of "Millennium Munch", 2.85, and 350.
Also, the program should use a function that takes a reference to a CandyBar as an argument and displays the contents of the structure.
Use const where appropriate.
*/

#include "stdafx.h"
#include <iostream>
#include <cstring>
using namespace std;
const int max = 20;

struct CandyBar
{
	char name[max];
	double weight;
	int calories;
};

void set_structure(CandyBar & cb, const char * str = "Millennium Munch", double w = 2.85, int c = 350);
void display(CandyBar & cb);

int main()
{
	
	CandyBar crunch;
	set_structure(crunch);
	display(crunch);
	const char * bar_name = "Yumness";
	double grams = 3.5;
	int cals = 400;
	set_structure(crunch, bar_name, grams, cals);
	display(crunch);
	system("pause");
    return 0;
}

void set_structure(CandyBar & cb, const char * str, double w, int c)
{
	
	strncpy_s(cb.name, str, sizeof(str));
	cb.weight = w;
	cb.calories = c;
}

void display(CandyBar & cb)
{
	cout << "Name: " << cb.name << endl;
	cout << "Weight: " << cb.weight << endl;
	cout << "Calories: " << cb.calories << endl;
}
Last edited on
It displays 4 characters because you only copy 4. strncpy_s(cb.name, str, sizeof(str));
sizeof(char*) is 4 bytes on a 32bit system.
To get the length of a C style string you need to use the strlen function.
That solved it. Thank you!
Topic archived. No new replies allowed.