Thread: Dinamic array

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

    Join Date
    Feb 2013
    Posts
    10
    Rep Power
    0

    Unhappy Dinamic array


    Code:
     #include <stdio.h> 
    #include <stdlib.h> 
    #include <string.h>   
    void toLower(char *v)  { 
    int i;      
    for (i=0; i<strlen(v); i++)        
     if ( (v[i]>='A') && (v[i]<='Z') ) v[i]+=32; } 
     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:"); 
     for(i=0; i<size-1; i++){         
    if(v[i] <= '9' && v[i] >= '1' )  continue;         
    else  printf("%c ", v[i]);}   
    printf( "Elementi nell'array convertiti:" );      
    toLower(v);      
    printf ("%s\n", v );     
    free(v); 
    return 0; }
    Hi , i have a problem with mt code.. I absolutely don't know white si wrong.. Pleiade someone help me! I have a problem with The function think but i don't know how tocorrect my code
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,143
    Rep Power
    2222
    When you call realloc the first time, the pointer, v, has not been initialized yet. It contains a random address. realloc needs that pointer in order to read from the previously allocated memory and then to free that previously allocated memory. Instead, you end up trying to access memory that's being used for something else or by another process, which usually causes your program to crash (terminate abruptly).

    You need to first assign a valid pointer value to v by calling either malloc or calloc.

    Also, in the future please tell us what the symptoms of the problem are. That will give us more to work with.

    Also please learn a formatting style that is more orderly.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    10
    Rep Power
    0
    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; }
    Yesterday i wrote The first part of The code (here) that i post and i test it, it's all ok.. I tested also The function and it's allright.. The problem became when i join The Two part because when The program should print The second printf, The output is 0.

    For exemple , if i write

    A
    8
    B

    AB
    ab

    Should be The correct output but in "ab" The output is 0 :confused:


    Sorry for The comment in The code but i'm italian :)
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    10
    Rep Power
    0
    I tried to correct and correct The code but The output for the last printf it still 0..


    Code:
     #include <stdio.h> 
    #include <stdlib.h> 
    #include <string.h>   
    void toLower(char *v)  { int i;      
    for (i=0; i<strlen(v); i++)           // Se il carattere corrispondente della stringa è un carattere maiuscolo, ovvero è compreso tra A e Z...           if ( (v[i]>='A') && (v[i]<='Z') ) v[i]+=32; }   
    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:"); // stampa normalmente l'intero array nominato v[]    
    for(i=0; i<size; i++){         
    if(v[i] <= '9' && v[i] >= '1' )  continue;         
    else  printf("%c ", v[i]);}   
    printf( "Elementi nell'array convertiti:" );    
    for (i=0; i<size; i++) {             
    toLower(v);      
    printf ("%c\n",v); }    
    free(v); 
    return 0; }
  8. #5
  9. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,376
    Rep Power
    1871
    Firstly, your code formatting is awful.
    Pick a style and apply it consistently.

    Try this
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    // Se il carattere corrispondente della stringa è un carattere maiuscolo, ovvero è compreso tra A e Z...
    void toLower(char *v)
    {
      int i;
      for (i = 0; i < strlen(v); i++) 
        if ((v[i] >= 'A') && (v[i] <= 'Z'))
          v[i] += 32;
    }
    
    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:"); // stampa normalmente l'intero array nominato v[]
      for (i = 0; i < size; i++) {
        if (v[i] <= '9' && v[i] >= '1')
          continue;
        else
          printf("%c ", v[i]);
      }
    
      printf("Elementi nell'array convertiti:");
      for (i = 0; i < size; i++) {
        toLower(v);
        printf("%c\n", v);
      }
      free(v);
    
      return 0;
    }
    Next, get a compiler with lots of warnings, and enable them.
    Code:
    $ gcc -W -Wextra -std=c99 bar.c
    bar.c: In function ‘toLower’:
    bar.c:9:17: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
    bar.c: In function ‘main’:
    bar.c:40:5: warning: format ‘%c’ expects argument of type ‘int’, but argument 2 has type ‘char *’ [-Wformat]
    Two things spring to mind.
    > toLower(v);
    > printf("%c\n", v);
    1. toLower works on the whole string, so there is no point calling it in a loop.
    2. The format to print a string (like the error message says) is %s, not %c
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    10
    Rep Power
    0
    Originally Posted by salem
    Firstly, your code formatting is awful.
    Pick a style and apply it consistently.

    Try this
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    // Se il carattere corrispondente della stringa è un carattere maiuscolo, ovvero è compreso tra A e Z...
    void toLower(char *v)
    {
      int i;
      for (i = 0; i < strlen(v); i++) 
        if ((v[i] >= 'A') && (v[i] <= 'Z'))
          v[i] += 32;
    }
    
    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:"); // stampa normalmente l'intero array nominato v[]
      for (i = 0; i < size; i++) {
        if (v[i] <= '9' && v[i] >= '1')
          continue;
        else
          printf("%c ", v[i]);
      }
    
      printf("Elementi nell'array convertiti:");
      for (i = 0; i < size; i++) {
        toLower(v);
        printf("%c\n", v);
      }
      free(v);
    
      return 0;
    }
    Next, get a compiler with lots of warnings, and enable them.
    Code:
    $ gcc -W -Wextra -std=c99 bar.c
    bar.c: In function ‘toLower’:
    bar.c:9:17: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
    bar.c: In function ‘main’:
    bar.c:40:5: warning: format ‘%c’ expects argument of type ‘int’, but argument 2 has type ‘char *’ [-Wformat]
    Two things spring to mind.
    > toLower(v);
    > printf("%c\n", v);
    1. toLower works on the whole string, so there is no point calling it in a loop.
    2. The format to print a string (like the error message says) is %s, not %c

    First of all Thanks.. but i have no idea to solve the problem 1.. If i shift The calling function before The loop i don't solve The problem because The output about The second string is anyway 0
  12. #7
  13. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,376
    Rep Power
    1871
    Have you tried stepping through this with a debugger.
    Focus ALL your attention on what is stored in size, and how you use it.
    Code:
      char size = 0;
      int i;
    
      do {
        printf("Inserire un nuovo elemento nell'array :");
        scanf("%c", &val);
        v = (char *) realloc(v, (++size) * (sizeof(char)));  //!! size is now 1, and 1 byte allocated
        v[size] = val;  //!! oh no, you just accessed v[1], which is 1 off the end of the array.
      }
      while (val != '0');
    Another thing you don't do is append a \0 character to mark the end of the string.

    Get the first loop working, before you add any more code to do things like toLower() or whatever.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    10
    Rep Power
    0
    I try to solve my problem like this .. I don't have changed The second printf because, as The first i don't want print numbers..there is something logic in my solution ? :(


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    
    char* toLower(char *v)  {
    int i, j=0;
    char *tmp; 
    tmp = (char*)malloc(strlen(v)*sizeof(char));    
       for(i=0; i<strlen(v); i++){
          tmp[i] = tolower(toascii(v[i])); 
       }
    return tmp; 
    }
    
    void my_printf(char *v){
    int i; 
    
       for(i=0; i<strlen(v); i++){
          if(v[i] <= '9' && v[i] >= '1' )  continue;
            else  printf("%c", v[i]);
         }
    }
    
    int main()  {
    char *v = NULL, *low=NULL;
    char val;
    int size = 0;
    int i, j;
    
       printf ( "Inserire elementi nell'array :\n");
    
    for(i=0; ; i++){
       scanf("%c", &val); 
       if( val == '0') break; 
       else{
          v = (char*)realloc(v, sizeof(char)); 
          v[i] = val; 
          getchar(); //Elimina il newline
       }
    }
    
    
        printf( "Elementi nell'array:\n"); 
       my_printf(v); 
    
         
        printf("\nStringa convertita:\n"); 
       char *x; 
       x=toLower(v);
       
       printf("%s\n", x); 
    
        return 0; 
    }

IMN logo majestic logo threadwatch logo seochat tools logo