C language, changing char variables

Viewed 321
int main()            
{  
      charactername="tom";        
      characterage=78;       
      printf("his name is %s\n", charactername);        
      printf("his age is %d\n", characterage);         

      characterage=78;
      charactername="John";
      printf("his name changed to %s\n", charactername);
      printf("his age changed to %d\n", characterage);
 
      return 0;
}
    

when I change the character name in between the code, the code does not run whereas if I only change the age the code run perfectly ,why can't I change the character variable but i can change the characters age??(in c language)

1 Answers

Two things:

  1. You must define the type of variables.
  2. Arrays cannot be assigned.

In your code, you need to make some changes (marked in comments below)

#include <stdio.h>
#include <string.h>
                                                 // header files are needed
#define ARRSIZ 64                               // choose any size you like 
int main(void)                                  // proper signature
{  
      char charactername[ARRSIZ]="tom";        //define a char array and initialize it.
      int characterage=78;                     // type is a must
      printf("his name is %s\n", charactername);        
      printf("his age is %d\n", characterage);         

      characterage=78;                           // this is fine, only assignment
      strcpy(charactername,"John");              // use strcpy to copy to an array
      printf("his name changed to %s\n", charactername);
      printf("his age changed to %d\n", characterage);
 
      return 0;
}
Related