Home > OS >  How to de-allocate an array of characters in c?
How to de-allocate an array of characters in c?

Time:03-10

I'm writing a program that asks the number of strings which i'll then count how many spaces it has. My problem is when I start a new cycle I can't allocate the array of characters I use to count the spaces. Thanks in advance.

#include <stdio.h>
#include <string.h>
int main(){
    char a[20];
    int x, z, esp=0, num;
    scanf("%d\n", &num);
    
    int array[num];
    
    for (int i=0;i<num;i  ){
       
        scanf("%[^\n]", &a);
    
        z =strlen(a);
    
        for (x=0; x<=z; x  ){
            if (a[x] == ' '){
            
                esp  ;
            } 
        }
        array[i] = esp;
        esp =0;
        
    }
    
    for (int i=0;i<num;i  ){
        printf ("%d\n", array[i]);
    }
return 0;
}

CodePudding user response:

Problems:

  • Not having all warnings enabled. Save time, enable them all.

  • '\n' blocks for more input in scanf("%d\n", &num);

  • Not checking scanf() return value.

  • Not limiting input with a width in scanf("%[^\n]", &a);

  • Wrong type passed in scanf("%[^\n]", &a);

  • Big one: not consuming the end-of-line with repeated scanf("%[^\n]", &a); calls.

  • Perhaps more.

Repaired code:

// scanf("%d\n", &num);
if (scanf("%d", &num) != 1) {  // '\n' removed
  puts("Error1");
  return -1;
}


    // scanf("%[^\n]", &a);
    if (scanf(" [^\n]", a) != 1) {  // ' ' consumes white-space like \n
      puts("Error2");
      return -1;
    }

CodePudding user response:

On the first scanf, remove \n character, after the first scanf, add getchar() to consume new line character. Replace second scanf with gets;

Then it will work correctly.

By the way, since gets is unsafe, you can use fgets with stdin parameter and max character count parameter instead of gets.

  •  Tags:  
  • c
  • Related