2

I have a char pointer.

char *ch;
char arr[100];

Now I want to store the value of the char array ch is pointing to in another array arr. I want to store the value pointed to by ch permanently, so that any other operation performed on ch will not modify the original value of array.

Can anyone tell me how to do this?

Saksham
  • 9,037
  • 7
  • 45
  • 73
sara
  • 95
  • 5
  • 14

3 Answers3

3

If ch contains data, copy the contents of ch.

memcpy(arr, ch, 100);

Caution: This solution assumes that ch references a memory location with at least 100 byte.

If ch contains a string, use the following:

strncpy(arr, ch, 99);
arr[99] =0;
Scolytus
  • 16,338
  • 6
  • 46
  • 69
  • can i get the length of ch? because ch was referred to a char array after strtok function was called – sara Sep 28 '13 at 17:16
  • The `strncpy` function will handle this. But, as others, I would recommend using `String` if you can. – Scolytus Sep 28 '13 at 17:20
3

In case you just want to copy the contents of an array (single block of memory) into another array, you can use memcpy:

memcpy(arr, ch, size);

where size is the size of an array pointed by ch (in bytes).

But since this is C++, using STL containers such as std::vector instead of C-style arrays would be more reasonable ~> instead of copying the memory you would be constructing and copying objects, e.g.:

std::vector<char> v(ch, ch + size);

But since you mentioned that ch is actually a return value of strtok, note that "Each call to strtok() returns a pointer to a null-terminated string containing the next token.", meaning you might use it to construct an object of type std::string:

std::string myStr(ch);

or yet even better: avoid using C-style strtok at first place. See: Split a string in C++?

Community
  • 1
  • 1
LihO
  • 41,190
  • 11
  • 99
  • 167
0

If you want ch to reference arr but not be able to modify it then you can do

const char* ch;
char* arr;

ch = arr;

This makes it so that the contents can still be modified using the original array, but not the pointer. I.e.:

arr[0] = 'g';  // valid operation
ch[0] = 'g';   // compiler error; modifying a const
Edward
  • 235
  • 4
  • 18