[En-Nut-Discussion] Passing String between Function and Prog_char

Trevor O'Grady togrady at comtech.uk.com
Wed Jun 30 12:26:15 CEST 2004


You a are copying a string into temp but you have not declared any space for
temp - temp is just a pointer and you have not pointed it anywhere. You need
to reserve memory if you want to store a string at this location e.g. char
temp[10];

Even with this you should not be returning temp as it is a local variable
and will no longer "exist" once the function returns. You could make it
static but it is not good programming practice to make variables static
unless they need to be. A better (and standard) solution is to specify where
you want the string copied to when you call the function (but remember to
allocate space for the sting first)


so change

char *FunctionA(int a){
static prog_char line1 = "a";
static prog_char line2 = "a";
char *temp;
if (a==1)strcpy_P(temp,line1);
return temp;}

to

void FunctionA(int a, char *string){
static prog_char line1 = "a";
static prog_char line2 = "a";
char *temp;
if (a==1)strcpy_P(string,line1);}

and call like this

char myString[21];
FunctionA( 1, myString);

You also need to consider what happens to myString when a is 0 i.e. it will
not be terminated.

Regards
Trevor
  -----Original Message-----
  From: en-nut-discussion-bounces at egnite.de
[mailto:en-nut-discussion-bounces at egnite.de]On Behalf Of iVesWorking
  Sent: 30 June 2004 11:01
  To: en-nut-discussion at egnite.de
  Subject: [En-Nut-Discussion] Passing String between Function and Prog_char


  i Had some problem of passing string from on function to the other.
  the case is like this

  char *FunctionA(int a){
  static prog_char line1 = "a";
  static prog_char line2 = "a";
  char *temp;
  if (a==1)strcpy_P(temp,line1);
  return temp;}

  char *FunctionB(int a){
  static prog_char line1 = "a";
  static prog_char line2 = "a";
  char *temp;
  if (a==1)strcpy_P(temp,line1);
  return temp;}

  char *functionC(void){
  char *temp1;
  char *temp2;
  char *temp3="hello world";
  strcpy_P(temp1,FunctionA(1));
  strcat(temp1,temp3);
  strcat_P(temp1,FunctionB(1));
  return temp1;
  }


  The real case the string are longer, but total length was around 30-100
char
  anyone have this problem ? or know why this happen ?
  or it was work flawless on your machine ?
  i using Gcc compiler
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.egnite.de/pipermail/en-nut-discussion/attachments/20040630/c5346aac/attachment-0001.html>


More information about the En-Nut-Discussion mailing list