Sam Kohnson
Sam Kohnson

Reputation: 115

Iterate through a char pointer from a struct

So I'm trying to combine two strings together but I'm getting str is a read only value on the last line of the second while loop. Is their anyone can I do this without changing the function header?

Also String is a struct I created that has a *char called str.

String * String_Combine(String * tar, const String * src) {
//end of string
  while (* tar->str != '\0') {
    tar->str++;
  }
//int i = 0;
//copy string
  while (*source->str != '\0') {
    *tar->str = *src->str;
    *tar->str++;
    *src->str++;
    // i++;

  }
return tar;
}

Upvotes: 2

Views: 378

Answers (2)

printfmyname
printfmyname

Reputation: 971

Two things:

  1. Make sure you allocate enough memory for tar->strto hold both tar->str and src->str
  2. Store a pointer tar/src->str locally and iterate thought them so you wouldn't loose the pointer to original str;

I wrote a test case for you to understand it easily ;)

#include <iostream>
#include <string.h>
struct String {
    char* str;
};
using namespace std;
String * String_Combine(String * tar, const String * src) {
// take a local copy of strs
char* tar_str = tar->str;
char* src_str = src->str;
//end of string
while (* tar_str != '\0') {
    tar_str++;
}

//int i = 0;
//copy src string to tar string
  while (*src_str != '\0') {
    *tar_str = *src_str;
    *tar_str++; 
    *src_str++;
    // i++;

  }
return tar;
}
int main()
{
    String* src = (String*) malloc(sizeof(String));
    src->str  = new char[20];
    strcpy(src->str, "World!");

    String* tar = (String*) malloc(sizeof(String));
    tar->str = new char[20];
    strcpy(tar->str, "Hello ");
    String* result = String_Combine(tar,src);

   cout << result->str << endl; 

   return 0;
}

Upvotes: 0

MikeCAT
MikeCAT

Reputation: 75062

Copy the pointer before modifying it. I guess modifying tar->str may also be harmful because it will destroy the information that where the string starts.

String * String_Combine(String * tar, const String * src) {
  char * tar_str = tar->str, * src_str = src->str;
  //end of string
  while (* tar_str != '\0') {
    tar_str++;
  }
  //int i = 0;
  //copy string
  while (*src_str != '\0') { /* assuming that "source" is a typo and it should be "src" */
    *tar_str = *src_str; /* with hope that there is enough writable buffer allocated */
    tar_str++;
    src_str++;
    // i++;

  }
  //terminate string
  *tar_str = '\0';
  return tar;
}

Upvotes: 2

Related Questions