用C语言强制转换指针
我创建了一个函数,它返回指向自制结构对象的指针。然后,我声明了另一个指针,我将其设置为前面提到的函数返回的指针。我得到错误“赋值从整数生成指针而不进行强制转换”-但我不明白为什么我应该强制转换。。。因为所有这些指针都被声明为同一类型 在disk.h中,我定义了以下内容:用C语言强制转换指针,c,pointers,C,Pointers,我创建了一个函数,它返回指向自制结构对象的指针。然后,我声明了另一个指针,我将其设置为前面提到的函数返回的指针。我得到错误“赋值从整数生成指针而不进行强制转换”-但我不明白为什么我应该强制转换。。。因为所有这些指针都被声明为同一类型 在disk.h中,我定义了以下内容: struct generic_attribute{ char *name; int current_value; int previous_value; //int time_series[500
struct generic_attribute{
char *name;
int current_value;
int previous_value;
//int time_series[500];
};
在disk.c中,我为generic_属性创建了一个构造函数,如下所示:
#include "disk.h"
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
struct generic_attribute* construct_generic_attribute(char* name, int current_value){
struct generic_attribute *ga_ptr;
//ga_ptr = (struct generic_attribute*) malloc (sizeof(struct generic_attribute));
ga_ptr = malloc (sizeof (struct generic_attribute));
ga_ptr -> name = name;
ga_ptr -> current_value = current_value;
ga_ptr -> previous_value = 0;
return ga_ptr;
}
我不明白为什么
ga_指针
被声明为指向类型struct generic_属性
的指针。函数construct\u generic\u attribute
的返回也是如此。我是C语言的新手,所以我可能会误解所有这些是如何工作的 您没有在disk.h
中声明construct_generic_attribute()
,因此在看到函数调用时,编译器假定它具有默认签名——即int construct_generic_attribute()代码>
感谢您对此提出质疑,而不是盲目地添加cast(这似乎很有效!)在disk\u test.c
中添加以下行:
struct-generic\u-attribute*构造\u-generic\u-attribute(char*,int)代码>头文件disk.h中缺少函数声明
添加声明:
struct-generic\u-attribute*构造\u-generic\u-attribute(char*,int)代码>
编译器将知道函数的返回类型是指针 首先,您使用了错误的格式说明符-您没有在编译器上启用足够严格的警告,或者您忽略了它们。@DieterLücking不是msvc
的特定错误。C11和Foreers与非常旧的C版本向后兼容。但是,好的,警告是受欢迎的(默认情况下,AFAIK gcc会警告您)。@rakeb.void一点也不,抱歉!再次强调,disk\u test.c
,而不是disk\u test.h
xd感谢您的回答。我在disk.h和disk.c中都尝试了这个声明,两种方法都有效。将其包含在disk.c中是一种惯例吗?还是有其他的选择原因?@Peregring lk等等,什么?现在你把我弄糊涂了。定义在disk.c
中,因此原型应该在disk.h
中。这个答案是traincraw x)@user2707197您可能是指disk.h
和disk\u test.c
(disk.c
已经在您定义它的地方有了函数签名)。由于此函数将与generic\u属性
struct一起使用,因此将其与struct一起声明更有意义。在技术层面上,只要编译器在函数调用之前遇到签名,就没有什么区别。@Quentin如果disk_test.c在同一个库(程序)中,这很好。不是暴露内部,而是遇到可维护性问题。@DieterLücking我在这里完全失败了。抱歉弄得一团糟!
#include "disk.h"
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
void test_generic_attribute_constructor(char* name, int current_value){
struct generic_attribute* ga_ptr;
ga_ptr = construct_generic_attribute(name, current_value);
printf("%i\n", construct_generic_attribute(name, current_value));
}
int main() {
test_generic_attribute_constructor("test", 2000);
}
ga_ptr = construct_generic_attribute(name, current_value);