Expression must be a modifiable lvalue pointer-to-char parameter
This is the whole code. Upon compiling I get the error below:
error LNK2019: unresolved external symbol "void __cdecl CandyBarFunc(struct CandyBar &,char const *,double,int)" (?CandyBarFunc@@YAXAAUCandyBar@@PBDNH@Z) referenced in function _wmain
fatal error LNK1120: 1 unresolved externals
#include "stdafx.h"
#include <iostream>
using namespace std;
struct CandyBar
{
char name[40];
double weight;
int calories;
};
void CandyBarFunc(CandyBar & astruct, const char * aname = "Millennium Munch", double aweight = 2.85, int acalories = 350);
void CandyBarFunc(const CandyBar & astruct);
int _tmain(int argc, _TCHAR* argv[])
{
CandyBar MyCandyBar;
C开发者_如何学CandyBarFunc(MyCandyBar, "Hello World Candy Bar", 1.25, 200);
CandyBarFunc(MyCandyBar);
return 0;
}
void CandyBarFunc(CandyBar & astruct, char * aname, double aweight, int acalories)
{
strncpy(astruct.name,aname,40);
astruct.weight = aweight;
astruct.calories = acalories;
}
void CandyBarFunc(const CandyBar & astruct)
{
cout << "Name: " << astruct.name << endl;
cout << "Weight: " << astruct.weight << endl;
cout << "Calories: " << astruct.calories;
}
Since name
is defined as char name[40]
, you cannot write astruct.name = aname
which is trying to change the address of name
array. But address of an array cannot be changed. Hence the error.
Do this: strcpy(astruct.name, aname);
Better yet, define CandyBar
as,
struct CandyBar
{
std::string name;
double weight;
int calories;
};
Now you can write : astruct.name = aname;
You cannot write char * aname = "Millenium Falcon"
, because "Millenium Falcon"
is a (const char *)
, a non-modifiable are of memory. Change your function signature to accept a const char * aname
if you can. Or use a std::string instead, you're writing C++ after all.
You have CandyBar.name defined as an array, which is not the same as a char pointer. You would have to use something like strcpy instead of the assignment statement. It would be even better to just use STL strings.
As per your comment question see here.
As the question is currently phrased, what is missing is the ; after the closing brace of struct CandyBar.
Use this:
strncpy(astruct.name, aname, sizeof(astruct.name));
astruct.name[sizeof(astruct.name)-1] = 0;
EDIT: And in response to your completely changed question:
"char * aname" is not the same as "const char * aname". You forward declare one (which gives the unresolved external) and then implement the other, which is never called.
精彩评论