c - 我收到错误 "warning: assignment to ' char' from 'char *' made integer frompointer without a Cast”

标签 c pointers struct malloc

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);
}

当我尝试运行上面的代码时,我收到一条警告“警告:从‘char *’对‘char’的赋值使指针中的整数不进行强制转换”,并且输出为“(null)”。我做错了什么?

最佳答案

*tempStudent[0].nametempStudent[0].name[0] 完全相同。 IE。它是一个 char 元素。

您需要将字符串复制到数组name中:

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

并且在打印时也使用数组本身:

printf("%s\n", tempStudent[0].name);

关于c - 我收到错误 "warning: assignment to ' char' from 'char *' made integer frompointer without a Cast”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66597142/

相关文章:

c++ - 当向 CURLOPT_DNS_SERVERS 提供错误 ip 时,Curl 返回全部正常

c - memmem 是 GNU 扩展有什么特别的原因吗?

c++ - 不确定为什么对象是本地的而不是引用的

c++ - shared_ptr with = symbol not allowed

c - 从指针数组中替换特定字符

python - 从文件中读取结构体数组

c - 我怎样才能 typedef 一个函数指针,它接受一个自己类型的函数作为参数?

C# - 将结构从一个对象传递到另一个对象

c - 为什么我的答案是 0.00.. 混淆如何将 int 转换为 float 结构

c - Pthread 同步问题