LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 07-22-2003, 06:42 AM   #1
sathyan
LQ Newbie
 
Registered: Feb 2003
Location: India
Distribution: Red Hat 9
Posts: 24

Rep: Reputation: 15
Copy a char* to another char*


Hello Guys,

I read in a book that to copy a char array to another char array, we can just copy the memory location. The program is :

#include <iostream>
using namespace std;

int main() {
char *p = "sample";
char *q = 0;

while ( *q++ = *p++);

cout << p << endl << q << endl;

return 0;
}

The program compiles fine, but when I try to run it, it generates an memory exception error.

I need to know whether this method is correct or if the method has any error in it.

Thanks for any who help.!
 
Old 07-22-2003, 07:58 AM   #2
TheLinuxDuck
Member
 
Registered: Sep 2002
Location: Tulsa, OK
Distribution: Slack, baby!
Posts: 349

Rep: Reputation: 33
Probably what you read was simply assigning the memory address of the original char array to the copy. Something like:
Code:
  char *original = "This is an original string.\0";
  char *copy;

  copy = original;
This doesn't actually copy anything more than the memory address. If you make changes to the char array in either spot, the changes will be reflected in both places, because they are sharing the memory address.

In order for your example to work without causing memory errors, you'll need to allocate enough space in the new location for the copy. Also, the string copy loop should be checking for a null terminator as it's basis for loop-termination.

It's also a good idea to include some length checking, to make sure that the copy's length doesn't exceed it's storage space allotment.
 
Old 07-22-2003, 08:02 AM   #3
lyle_s
Member
 
Registered: Jul 2003
Distribution: Slackware
Posts: 392

Rep: Reputation: 55
Re: Copy a char* to another char*

Quote:
Originally posted by sathyan

char *q = 0;

while ( *q++ = *p++); // q is 1 when you attempt to dereference it.
This method has an error: you're attempting to dereference a pointer with the value 1, i.e. q.

Lyle
 
Old 07-22-2003, 08:08 AM   #4
kev82
Senior Member
 
Registered: Apr 2003
Location: Lancaster, England
Distribution: Debian Etch, OS X 10.4
Posts: 1,263

Rep: Reputation: 51
Quote:
Also, the string copy loop should be checking for a null terminator as it's basis for loop-termination.
it is, but yes you need to allocate memory to copy it to, something like this:

Code:
char *p="sample";
char q[10];

while( *q++ = *p++ );
now q contains a copy of p. the best way to do it however is using the functions defined in string.h or cstring since it looks like your using c++. if you are happy using c++ then use the std::string class from stl its much better.
 
Old 07-22-2003, 08:44 AM   #5
TheLinuxDuck
Member
 
Registered: Sep 2002
Location: Tulsa, OK
Distribution: Slack, baby!
Posts: 349

Rep: Reputation: 33
Quote:
Quote:
Also, the string copy loop should be checking for a null terminator as it's basis for loop-termination.
Originally posted by kev82
it is
It is? Are you sure? My tests prove otherwise, but if so, I'd like to understand how it's doing so, so that I may take advantage of it in the future. (ok, I just got it to compile, but I get the compiler warning "suggest parentheses around assignment used as truth value", which I'm not quite sure how to solve, since I've never used this method of string copying before)

Quote:
Code:
char *p="sample";
char q[10];

while( *q++ = *p++ );
now q contains a copy of p.
Actually, that won't work, because it's trying to increment the memory address of a predefined char array. This is definitely not the same thing as a pointer to a char array. Upon trying to compile said code, I receive this error:

Code:
~> g++ -Wall -o test test.c
test.c: In function `int main()':
test.c:10: non-lvalue in increment
And, even if it did work, now both pointers are pointing to the ends of the strings (I think 1 char past the null terminator), and not the beginnings.

The code would need to take a pointer placeholder to q, and use it for incrementation, instead of the original.

Also, this loop still doesn't do any length checking (a big no-no in my book).
 
Old 07-22-2003, 10:35 AM   #6
kev82
Senior Member
 
Registered: Apr 2003
Location: Lancaster, England
Distribution: Debian Etch, OS X 10.4
Posts: 1,263

Rep: Reputation: 51
sorry, im not thinking properly, of course you cant change the value of a constant pointer, the code i meant to post was the following:

Code:
char a[10], *b="sample\n";
char *c=a, *d=b;

while(*c++=*d++);
printf("%s", a);
edit: the reason it works is the statement *c++=*d++ evaluates *d so when the null terminator is copied the expression evaluates to zero which automatically terminates the loop.

Last edited by kev82; 07-22-2003 at 10:39 AM.
 
Old 07-22-2003, 01:36 PM   #7
rmartine
Member
 
Registered: Dec 2002
Location: San Luis Obispo, CA
Distribution: Fedora Core 3
Posts: 618

Rep: Reputation: 30
This should copy a string byte by byte.

Source: http://www.metalshell.com/static/code_14.shtml
Code:
#include <stdio.h>
#include <stdlib.h>

void strcopy(const char *, char *);

int main() {
  char string1[] = "This is string1";
  char string2[] = "This is string2";

  strcopy(string1, string2);
  printf("String2: %s", string2);
}

void strcopy(const char * str1, char * str2) {
  int x = 0;

  /* change the size of string2 to the size of string1 */
  realloc(str2, sizeof(str1));

  do {
    str2[x] = str1[x];
  } while (str1[x++] != '\0');

}

realloc() should behave like malloc() if str2 is NULL. Hope this helps.

Last edited by rmartine; 07-22-2003 at 01:39 PM.
 
Old 07-22-2003, 10:51 PM   #8
sathyan
LQ Newbie
 
Registered: Feb 2003
Location: India
Distribution: Red Hat 9
Posts: 24

Original Poster
Rep: Reputation: 15
I thank all of you for your replies. I generally use C++ string functions, but I read about this type of copying in Stroustrup's "The C++ Programming Language", and I could not get it to work for me. I thought that I must have done something wrong, but it seems that the method by itself is wrong.

Thanks again.
 
Old 07-24-2003, 06:15 AM   #9
DIYLinux
Member
 
Registered: Jul 2003
Location: NL
Distribution: My own
Posts: 92

Rep: Reputation: 18
Did you read the replies ? The method while(*q++ = *p++) is perfectly fine. Think Stroustrup, a software engineer with years of C experience and a doctoral degree got it wrong ?

You just forgot to allocate memory for the copy. Use malloc or calloc when doing C, new[] in C++, or allocate it on the stack (fast, but beware of dangling pointers on a return).

If you really want to program in C or C++, you must understand the way C/C++ programs execute. Pointers and references are just numbers that reference an address in memory. Defining a pointer variable does not allocate memory for the stuff it points, unless you use an initializer.

IMHO this is a major problem with C++. You still have to know the low level details. I learned assembly way before C and C++, and did not have too much trouble. If you come from some high level background, you will have a lot to learn.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
char to char* thanhVic Programming 1 04-04-2005 04:49 PM
C pointers confusion - char ** = char [][] ?? saravkrish Programming 12 12-02-2004 10:06 AM
C Problem---convert char to char* totti10 Programming 11 11-06-2004 11:32 AM
invalid conversion from `char' to `const char* bru Programming 6 05-09-2004 03:07 PM
convert from char* to unsigned char* D J Linux - Software 2 02-20-2004 04:09 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 09:39 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration