0

Is this expression correct?

{
    char a;
    char *temp;
    for(int j = 0; j < len; j++)
    {
        strcpy(&temp[j], (char*)a);
    }
}

in this code a gets updated externally by the user input/key stroke. I want to copy all incoming/updated a to the temp as an entire string.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Kiran
  • 63
  • 1
  • 2
  • 8
  • @ObscureRobot: You can do named links in comments with the [name](address) format. – Mankarse Nov 08 '11 at 05:30
  • that's a bug in StackOverflow's code that automatically turns short answers into comments. I thought I already deleted that comment, I've delete it once again. – ObscureRobot Nov 08 '11 at 19:42

3 Answers3

1

Since 'a' in your example is not null-terminated and you want to assign a single character in string buffer, you can do:

 int const buffer_size = 5;
 char a = 'c';
 char *temp = new char[buffer_size]; // Remember to allocate your string buffer
 temp[index] = a;
 // .....

 delete[] temp; // free buffer.

index is an int which you can use to keep track of next position in buffer.

cpx
  • 17,009
  • 20
  • 87
  • 142
0

No for a few reasons:

  • temp isn't initialised, it's pointing to some random location and doesn't have any memory allocated for it, so you're just going to be writing over a random part of memory (and/or crash).
  • a is a single char and you're treating it's value as a string (char*) using strcpy (I'm assuming you meant (char*)&a which is still wrong).
  • strcpy continues copying chars from the source (a) to the destination until it hits a '\0' in the source...which could be anywhere since a is not a NUL terminated string but a char.

If you want to write/append a single char to a string/buffer you just do buffer[position] = character, where buffer is a char[] or a char* pointing to a block of allocated memory, position is the position in the buffer you want to stick the char, and character is obviously that char.

Anyway, I've got no idea what you're trying to do or the logic behind why you're trying to do whatever it is you're trying to do like this.

EDIT: And also you have this tagged as C++, why aren't you using std::string and std::cin if you are in fact using C++?

AusCBloke
  • 18,014
  • 6
  • 40
  • 44
0

Your code is wrong in so many ways:

  1. You cannot cast a char to a char*. You have to do something like this: (char *)&a; and since a is a char, you don't need to cast it at all.

  2. You don't need to strcpy it. You can just do something like: temp[j] = a;

  3. char *temp has not associated memory assigned to it. So you need to do something like this: char *temp = malloc(sizeof(char) * len);

Complete code here:

{
 char a = myFunToGetInput();
 char *temp = malloc(sizeof(char) * len));
 for(int j = 0; j < len; j++) {
   temp[j] = a;
 }
}

Or if you have used memset before:

{
 char a = myFunToGetInput();
 char *temp = malloc(sizeof(char) * len));
 memset(temp, (unsigned char)a, len);
}
mmtauqir
  • 8,499
  • 9
  • 34
  • 42