Concatenate in a cycle in C

1

I have a problem, when I want to go concatenating it is the variable of type string temp every time the cycle is repeated this variable is restarted. Why is this happening and what can I do to solve it?

void processData( int *digits, int digitLen ) {
  //char numLetter[];
  char temp[] = "";
  int i,c,j;

  if( digitLen >= 3 ) {
    int m = digitLen - 2;
    // restamos 2 porque solo nos interesan aquí los número
    // a partir de 3 dígitos, es decir, a partir de 100

    for( i = m, j = m - 1, c = 0; i >= 1; i--, j--, c++ ) {
      int g = digits[c]-1; // take the number to add the unit

      if( g == 0 )
        continue;

      strcat(temp,a[0][g]);
      strcat(temp," ");
      strcat(temp,a[3][j]); 
      strcat(temp," ");
    }
    strcat(temp,"and ");
  }
  printf("%s \n",temp);
}

I am doing a program that returns a number in letter, for that I want to go adding concatenating to the variable temp. Thus: we assume the number is 1350. First temp="", the first number is traversed 1 then add temp="One thousand", then a space and concatenate: 3- > three hundred and temp would be temp="One thousand three hundred" and so, but when the cycle is repeated, what was previously in the temp variable is deleted.

    
asked by Ángel Barrios 26.02.2017 в 04:43
source

2 answers

1

The truth, I do not understand your code very well:

void processDataint( int *digits, int digitLen ) {

Do you pass a pointer to the whole? Is that because elsewhere you have decomposed the number to be processed in its different digits?

And I guess that a[] is of type char *a[] , an array of pointers to strings, in which you save the texts to add. However, then you do things like a[0][g] , with what would be char **a[] , but I can not think why.

Well, the subject. strcat( dest, other ) does not manage the memory ; it is assumed that, when calling it, dest has space to add the other string.

However, I do not see that you add that space. There are no calls to realloc( ) , nor to malloc( ) , nor to calloc( ) .

By doing so, you are overwriting the stack; the effect of this is undefined ; you may receive an operating system failure (general protection error type), overwrite the internal variables of the function, or any other curious effect.

Assuming we choose to call realloc( ) , tmp can not be on the stack ; it only serves for dynamic memory pointers, which requires a change in the declaration of temp :

char *temp = malloc( 1 );
*temp = 0;

The correct use of the strcat( ) function, in your case, would be something like:

....
  if( g == 0 )
    continue;

  lengthToAdd = strlen( a[0][g] ) + strlen( a[3][j] + 7;
  // " " + " " + "and " + '
char *tmp2;
size_t lengthToAdd;
' = 7; tmp2 = realloc( temp, sizeof( temp ) + lengthToAdd ); if( !tmp2 ) { // ERROR. NO HAY MEMORIA. } else { temp = tmp2; } strcat( temp, a[0][g] ); strcat( temp, " " ); strcat( temp, a[3][j] ); strcat( temp, " " ); } strcat( temp,"and " );

}

We would have to declare the variables involved:

void processDataint( int *digits, int digitLen ) {

With that, your chains will be added correctly.

    
answered by 26.02.2017 в 06:51
0

Maybe you could use sprintf, you start the string with a null character so that it does not throw errors at you, that I did in Latin to make the format of the date, something like this:

sis.fecha("el año de hoy es %a y el mes es %mm")

url: link

This is an example of how you could continue to copy more characters with sprintf in a cycle:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>


int main() {
    char *cadena = malloc(20); // indico el tamaño de la memoria que voy a usar
    sprintf(cadena, "%c", 0); // puedes ingresar un valor nulo para no tener errores en caso de iniciarla de 0
    char *cad1 = "123456"; // esta es una cadena donde ingreso los númericos que meteré en 'cadena'
    for (int i=0; i<strlen(cad1); i++) {
        sprintf(cadena, "%s%c", cadena, cad1[i]); // hago una copia de caracter por carater de 'cad1' a 'cadena', hago que retome lo que ya tiene cadena y siga copiando.
    }
    printf("%s\n", cadena); // imprimo el resultado
    free(cadena); // libero la memoria
}
    
answered by 09.03.2017 в 11:05