Thread: problem with syntax for declaring array

  1. #1
    Registered User
    Join Date
    May 2012
    Posts
    1

    problem with syntax for declaring array

    Code:
    //Plz sort out my problem
                                     
                                      #include<stdio.h>
    
    				  struct student
    				  {
    				  int num;
    				  char name[20];
    				  };
    
    			          int main(void)
    				  {
    				  struct student p;
    				  p.num=3;
    
    				  p.name="dilipkumar";          //whats wrong with this statement??
                                                                                      //how to initialise char array directly with string?
    				  FILE *fp;
    				  fp=fopen("cdk.txt","w");
    			          fwrite(&p,sizeof(struct student),1,fp);
    				  fclose(fp);
    			          return 4;
    				  }

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Code:
    p.name="dilipkumar";          //whats wrong with this statement??
    C doesn't allow to assign to an array.
    use strcpy()
    Code:
    strcpy(p.name,"dilipkumar");
    to initialize an array use

    Code:
    char arr[] = "dilipkumar";
    Kurt
    Last edited by ZuK; 05-15-2012 at 07:02 AM.

  3. #3
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    if you want to initialize a structure you could use
    Code:
        struct student s = {1, "joe"};
    Kurt

  4. #4
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    the real trouble here is that you posted C code to the C++ forum.

    there is a difference.

    if this is C, then use the C forum.

    if it's C++ then use proper C++ constructs and functions. use std::fstream and std::string instead of FILE* functions and char pointers/arrays.

    if you have a book that claims to teach C++, but teaches you C first, then you immediately need to find a different book.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem in declaring array size inside a function
    By dpitz in forum C Programming
    Replies: 14
    Last Post: 04-27-2012, 04:17 PM
  2. Array Syntax Versus Pointer Syntax
    By LyTning94 in forum C++ Programming
    Replies: 6
    Last Post: 12-06-2011, 10:56 AM
  3. Syntax for Declaring Functions in Dev-C++
    By Muz in forum C Programming
    Replies: 4
    Last Post: 07-03-2007, 04:53 AM
  4. Declaring array ..
    By winsonlee in forum C Programming
    Replies: 5
    Last Post: 04-24-2004, 05:00 AM
  5. declaring a large array problem !
    By Array_Troubled in forum C++ Programming
    Replies: 10
    Last Post: 01-08-2003, 06:02 AM

Tags for this Thread