reassign value to string

1

I have this assignment to a string:

unsigned char cadena[] = {154,162,162,145,'
unsigned char cadena[] = {154,162,162,145,'%pre%'};
'};

What is "hola" , but in decimal.

How can I reassign another decimal value to the same variable called string in this case?

strcpy does not work because its parameter is char*

    
asked by Alberto Figueroa 11.06.2018 в 20:24
source

3 answers

0

I answer to myself: It can not be in decimal, only in octal or hexadecimal:

strcpy(cadena, "\xa2\xa5\xab\x95\x9b\x93");
    
answered by 12.06.2018 / 12:34
source
1

Based on the comments:

  

But the size of the new arrangement differs from the first ??? - Dariel Ramos Díaz de Villegas

     

yes, it can be {2,2,2,2, '\ 0'}; the new value as {24,22,23,54,43,23 '\ 0'}; - Alberto Figueroa

I already notice that you are careful to exceed the initial size.

Before this statement:

unsigned char cadena[] = {154,162,162,145,'
unsigned char *ptr = 0;
size_t max_size;

max_size = 10;
unsigned char* ptr2 = (unsigned char*)realloc(ptrmax_size*sizeof(unsigned char));
if( 0 == ptr2 )
{
  /* Error al solicitar memoria */
}

ptr = ptr2;
'};

The program reserves 5 bytes for cadena . The rest of the memory will be available to other variables, then if you exceed that limit of 5 bytes you will end up stepping on the value of other variables and the program may behave erratically.

If your idea is to have an array of variable size you have to resort to dynamic memory. To request memory you can use malloc , but to modify the size of this assignment you have to resort to realloc . realloc can also be used to make the initial memory reservation, so it is up to you to choose the mechanism that best suits your needs:

unsigned char cadena[] = {154,162,162,145,'
unsigned char *ptr = 0;
size_t max_size;

max_size = 10;
unsigned char* ptr2 = (unsigned char*)realloc(ptrmax_size*sizeof(unsigned char));
if( 0 == ptr2 )
{
  /* Error al solicitar memoria */
}

ptr = ptr2;
'};

Note that the memory remapping may fail so it does not hurt to check the pointer that returns realloc .

After this you can copy the data into the memory as you have indicated in your answer.

    
answered by 12.06.2018 в 12:55
0

With strcpy if you can change the value to a char array as it passes as a pointer, you just have to cast it to (char *) because you have it as unsigned.

unsigned char cadena[] = {154,162,162,145,'
unsigned char cadena[] = {154,162,162,145,'%pre%'};
strcpy((char*)cadena, "Hello World!");
std::cout << "Probando: " << cadena << endl;
'}; strcpy((char*)cadena, "Hello World!"); std::cout << "Probando: " << cadena << endl;
    
answered by 11.06.2018 в 20:47