Link to home
Start Free TrialLog in
Avatar of anothercto
anotherctoFlag for United States of America

asked on

variable-length array?

What's wrong with this short program, and how do I make it work? (I do not want to fix/limit the size of the array to 10000.)

Thanks.
---------------
#include <stdio.h>
#include <stdlib.h>

void main(int argc, char** argv){
//  char content[10000];
  if(argc<3){
     printf("Usage: \n       sendfile number_of_bytes file_name\n");
     exit(0);
  }

  FILE* fout=fopen(argv[2],"w");
  int num=atoi(argv[1]);
int * size=(int *)malloc((size_t)num);
char content[*size];
  for(int i=0; i<num; i++)content[i]='a';
  fwrite(content,1,num,fout);
free(size);
}
ASKER CERTIFIED SOLUTION
Avatar of pagladasu
pagladasu

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of thienpnguyen
thienpnguyen

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


void main(int argc, char **argv)
{
    //  char content[10000];
    if(argc < 3)
    {
        printf("Usage: \n       sendfile number_of_bytes file_name\n");
        exit(0);
    }
    FILE * fout = fopen(argv[2], "w");

    if( fout == NULL )
        return;
   
    int       num = atoi(argv[1]);
    char *content = (char *)malloc(num*sizeof(int));

    if( content == NULL )
        return;
   
    for(int i = 0; i < num; i++)
        content[i] = 'a';
    fwrite(content, 1, num, fout);

    free(content);
    fclose(fout);
}

if you write in "pure" C, the code as following.


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


void main(int argc, char **argv)
{
    FILE * fout;
    int    num, i;
    char *content;

   
    //  char content[10000];
    if(argc < 3)
    {
        printf("Usage: \n       sendfile number_of_bytes file_name\n");
        exit(0);
    }

    fout = fopen(argv[2], "w");
    if( fout == NULL )
        return;
   
    num = atoi(argv[1]);
    content = (char *)malloc(num*sizeof(int));

    if( content == NULL )
        return;
   
    for(i = 0; i < num; i++)
        content[i] = 'a';
    fwrite(content, 1, num, fout);

    free(content);
    fclose(fout);
}

Avatar of anothercto

ASKER

thienpnguyen,

I'll post 50 points for you.
Thanks.