-1

I am new to c and I'm trying to assign values to a struct using strcpy(I've tried to use assignment using lvalue method and that throws an error). I try to run the program and nothing happens. Where is the error in my code? I'm using codeblocks to run the program.

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

int main(){
    struct student{
        char name[25];
        int age;
    };
    struct student s1;
    strcpy(s1.name, "Sammy");
    strcpy(s1.age, "18");
    printf("%s, %d", s1.name, s1.age);
}

The program doesn't run

Simson
  • 3,373
  • 2
  • 24
  • 38

3 Answers3

1

Remove this:

strcpy(s1.age, "18");

You can to normal assignment. s1.age = 18;

Mohan
  • 1,871
  • 21
  • 34
1

The first thing to do is to read the warnings from your compiler as they contain valuable information about problems with your code. Compiling the original code with gcc and clang gives these warnings:

clang:

so5.c:12:12: warning: incompatible integer to pointer conversion passing 'int' to parameter of type 'char *' [-Wint-conversion]

gcc:

so5.c:12:12: warning: passing argument 1 of ‘strcpy’ makes pointer from integer without a cast [-Wint-conversion] strcpy(s1.age, "18");

So the offending line is:

strcpy(s1.age, "18");

is first treating the uninitiated s1.age as pointer and tries to copy the string into this unknown location. This will very likely result in a segmenation fault.

You could of course make a pointer of this and fill its memory contents with the "18"

strcpy(&s1.age, "18");

But wait this results in a print like:

Sammy, 14385

Because the string is encoded in ascii, three bytes 0x31,0x38,0

When written into the location of the int age field as 0x003831 or in decimal 14385. This is however pure luck that the reaming byte(s) was randomly initiated to 0.

The correct way to assign age a value is with an assignment:

s1.age = 18;
Simson
  • 3,373
  • 2
  • 24
  • 38
0

strcpy() is used for copying strings to a character buffer. With strcpy(s1.age, "18");, you are trying to read something from the address of the string 18 and write to s1.age which is an int.

Either declare the age member to be a char array, just like you did for name (although this would restrict you from doing arithmetic operations on age). Or, use the assignment operator = to assign an int. Like: s1.age = 18;

babon
  • 3,615
  • 2
  • 20
  • 20