#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    10
    Rep Power
    0

    [C] convert array in string


    Code:
    #include <stdio.h>  
    #include <stdlib.h>  
    #include <string.h>    
    
    int main()  {        
        char *v=NULL ;          
        char val;          
        char size = 0;        
        int i;      
        do  {                
            printf ( "Inserire un nuovo elemento nell'array :");    
            scanf ("%c", &val);              
            v = (char*) realloc( v, (++size)*(sizeof(char)) );              
            v[size] = val;
        }  while (val != '0');      
        printf( "Elementi nell'array:");    
        for(i=0; i<size; i++){          
             if(v[i] <= '9' && v[i] >= '1' )  continue;          
             else  printf("%c ", v[i]);}      
        free(v);  
        return 0;
    }.
    I wrote this code to digit in input a dinamic array with indefinite elements (numbers and letters) and in The end , print this array but only letters elements. The code works perfectly but now i would like to convert my array in a string but i have no idea how to do it. Could someone help me please??
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,890
    Rep Power
    481
    Your program is not perfect. Each time you store a character into v you put it one position beyond the space allocated. Not only do you overwrite memory that is not yours, (certainly not v's), if reallocation moved the array rather than extending it you'd lose the character. Now, with slightly rewritten version of your program that displays the array, I give it the input
    2340
    the output is
    ^@234
    You didn't store a character at v[0].
    Code:
    #include <stdio.h>  
    #include <stdlib.h>  
    #include <string.h>    
    
    int main()  {        
        char *v=NULL ;          
        char val;          
        int size = 0;        
        int i;      
        do  {                
            printf ( "Inserire un nuovo elemento nell'array :");    
            scanf ("%c", &val);              
            v = (char*) realloc( v, (++size)*(sizeof(char)) );              
            v[size] = val;
        }  while (val != '0');      
        printf( "Elementi nell'array:");    
        for(i=0; i<size; i++)
          putchar(v[i]);
        putchar('\n');
        free(v);
        return 0;
    }
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,172
    Rep Power
    2222
    Originally Posted by ele9
    The code works perfectly but now i would like to convert my array in a string but i have no idea how to do it.
    All you need to do is to add one more character to the end of the char array you've created, the null-terminator, which is '\0' . A null-terminated char array is a C-style string.

    Well, you also need to make the correction that was pointed out to you.
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    10
    Rep Power
    0
    first of all Thanks to booth for your answer. I posted The wrong code ( i'm id**t) and now i tested it also with input 1240 and it should be ( i hope!) ok. About The NULL terminator string , could i use a cicle like this(?):

    Code:
        if ( v[i] == '\n' )
        {
            V[i] = '\0';
            break;
        }
    }






    Code:
    
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()  {
          char *v ; 
          char val; 
          int size = 0;
          int i;
    
    
    
    do  { 
    
                printf ( "Inserire un nuovo elemento nell'array :");
    
    
    scanf ("%c", &val);
                v = (char*) realloc( v, (++size)*(sizeof(int)) );
                v[size-1] = val;  
    
          } while (val != '0'); 
    
    
    printf( "Elementi nell'array:"); // stampa normalmente l'intero array nominato v[]
    
    
     for(i=0; i<size-1; i++){
            if(v[i] <= '9' && v[i] >= '1' )  continue;
            else  printf("%c ", v[i]);}
    
    
    free(v);
    return 0; }
  8. #5
  9. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,890
    Rep Power
    481
    Your new version is good, except that the NULL initial value
    char *v = NULL;
    in your original is critical. This version has a few other changes including changing the final '0' to nul making an ASCIIz string.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define ORIGINAL 1 /* setting ORIGINAL to 0 blocks digits from the string */
    
    int main()  {
      char *v = NULL;		/* = NULL   //IMPORTANT */
      char val;
      int size = 0;
      int i;
      do  {
        printf ( "Inserire un nuovo elemento nell'array :");
        scanf ("%c", &val);
    
        /* don't admit unwanted characters */
        if (ORIGINAL || (val <= '0') || ('9' < val)) {
          v = (char*)realloc(v,(++size)*(sizeof(int))); /* sizeof char was large enough */
          if (NULL == v) {	     /* handle the potential memory problem */
    	exit(1);
          }
          v[size-1] = val;
        }
      } while (val != '0');
      printf( "Elementi nell'array:"); // stampa normalmente l'intero array nominato v[]
    
      for(i=0; i<size-1; i++){
        if(v[i] <= '9' && v[i] >= '1' )  continue;
        else  printf("%c ", v[i]);
      }
    
      putchar('\n');
      v[size-1] = 0;		/* overwrite the '0' with ASCII nul */
      printf("As nul terminated string <%s>.\n",v);
    
      free(v);
      return 0;
    }
    Last edited by b49P23TIvg; February 11th, 2013 at 07:37 PM.
    [code]Code tags[/code] are essential for python code and Makefiles!
  10. #6
  11. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,172
    Rep Power
    2222
    No, you're exiting the loop before you get to the '\n', so that makes no sense.

    Rather, after you leave the do-while loop, you need:
    Code:
                v = (char*) realloc( v, (++size)*(sizeof(int)) );
                v[size-1] = '\0';
    And you also need to initialize that pointer, v, before you make the first call to realloc. I thought we discussed that before!

    Here is what the documentation says about realloc (http://www.manpagez.com/man/3/realloc/):
    The realloc() function tries to change the size of the allocation pointed
    to by ptr to size, and returns ptr. If there is not enough room to
    enlarge the memory allocation pointed to by ptr, realloc() creates a new
    allocation, copies as much of the old data pointed to by ptr as will fit
    to the new allocation, frees the old allocation, and returns a pointer to
    the allocated memory. If ptr is NULL, realloc() is identical to a call
    to malloc() for size bytes. If size is zero and ptr is not NULL, a new,
    minimum sized object is allocated and the original object is freed. When
    extending a region allocated with calloc(3), realloc(3) does not guarantee
    that the additional memory is also zero-filled.
    You should initialize v as
    char *v = NULL;
    Read the documentation on realloc to understand why.
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    10
    Rep Power
    0
    Thanks Thanks Thanks !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Finally my code works correctly!!!!!!!!!!!!!!!!! :googly:

IMN logo majestic logo threadwatch logo seochat tools logo