1
struct student {
    char name[30];
    char rollNumber[20];
    char class[2];
};

void test(int length){
    struct student* tempStudent = (struct student*)malloc((length+1)*sizeof(struct student));
    *tempStudent[0].name = "Hello";
    printf("%s", *tempStudent[0].name);

}

void main(){
    test(1);
}

When I try to run the above code, I get a warning "warning: assignment to 'char' from 'char *' makes integer from pointer without a cast" and the output as "(null)". What am I doing wrong?

Saarthak
  • 39
  • 1
  • 2
  • 5
  • You try to assign a pointer to a single character. That does no work. Also assigning a pointer to an array is not possible. – Gerhardh Mar 12 '21 at 09:19

1 Answers1

2

*tempStudent[0].name is exactly equal to tempStudent[0].name[0]. I.e. it's a single char element.

You need to copy the string into the array name:

strcpy(tempStudent[0].name, "Hello");

And also use the array itself when printing it:

printf("%s\n", tempStudent[0].name);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621