c语言中的结构
我得到以下程序的错误c语言中的结构,c,C,我得到以下程序的错误 #include "stdafx.h" #include<stdio.h> struct s { char *st; struct s *sp; }; struct s *p1,*p2; swap(p1,p2); int main() { int i; struct s *p[3]; static struct s a[]={ {"abc",a+1},{"def",a+2},{"ghi",a} }
#include "stdafx.h"
#include<stdio.h>
struct s
{
char *st;
struct s *sp;
};
struct s *p1,*p2;
swap(p1,p2);
int main()
{
int i;
struct s *p[3];
static struct s a[]={
{"abc",a+1},{"def",a+2},{"ghi",a}
};
for(i=0;i<3;i++)
{
p[i]=a[i].sp;
}
swap(*p,a);
printf("%s %s %s\n",p[0]->st,(*p)->st,(*p)->sp->st);
return 0;
}
swap(p1,p2)
{
char *temp;
temp = p1->st;
p1->st = p2->st;
p2->st = temp;
}
#包括“stdafx.h”
#包括
结构
{
char*st;
结构s*sp;
};
结构s*p1,*p2;
互换(p1,p2);
int main()
{
int i;
结构s*p[3];
静态结构s a[]={
{“abc”,a+1},{“def”,a+2},{“ghi”,a}
};
对于(i=0;ist,(*p)->st,(*p)->sp->st);
返回0;
}
互换(p1、p2)
{
字符*温度;
温度=p1->st;
p1->st=p2->st;
p2->st=温度;
}
如何使这个程序工作。即使我们没有把int放在交换之前,我希望它会默认为int
错误C4430:缺少类型说明符-假定为int。注:C++不
支持默认整数
错误C2078:初始值设定项太多
错误C2440:“正在初始化”:无法从“s*”转换为“int”
没有可以进行此转换的上下文
错误C2450:项不计算为包含2个参数的函数
错误C2456:“交换”:函数样式
试一试
您的
swap
函数不会返回任何内容。在C中,应该用p1
和p2
的类型:
void swap(struct s *p1, struct s *p2);
及
这是错误的。作为函数定义的一部分,您需要指定什么类型的
p1、p2
。即使是swap
函数的正向声明也是如此。还要提到它的返回类型。您的程序有很多错误。。。其中一些我无法纠正,因为我无法获得预期的行为
首先,您不需要全局声明要定义的函数的参数struct s*p1、*p2
。其次,函数原型必须包括所讨论的参数类型以及返回类型(在您的例子中为void)。第三,swap函数的第一个pamater是指向结构的指针,因此需要传递p`数组的第一个元素(指向s结构的指针)
下面的代码编译并不会对错误进行分段,即使我认为它的行为不是您所期望的
#include <stdio.h>
struct s {
char *st;
struct s *sp;
};
void swap(struct s *ptr1, struct s *ptr2);
int main() {
int i;
struct s *p[3];
static struct s a[]={ {"abc",a+1}, {"def",a+2}, {"ghi",a} };
for(i=0;i<3;i++) {
p[i] = a[i].sp;
}
swap(p[0], a);
printf("%s %s %s\n",p[0]->st,(*p)->st,(*p)->sp->st);
return 0;
}
void swap(struct s *ptr1, struct s *ptr2) {
char *temp;
temp = ptr1->st;
ptr1->st = ptr2->st;
ptr2->st = temp;
}
#包括
结构{
char*st;
结构s*sp;
};
无效交换(结构s*ptr1,结构s*ptr2);
int main(){
int i;
结构s*p[3];
静态结构sa[]={{“abc”,a+1},{“def”,a+2},{“ghi”,a};
对于(i=0;ist,(*p)->st,(*p)->sp->st);
返回0;
}
无效交换(结构s*ptr1、结构s*ptr2){
字符*温度;
温度=ptr1->st;
ptr1->st=ptr2->st;
ptr2->st=温度;
}
从技术上讲,它不必这样做。没有返回类型的函数默认为int
,而int
函数不必有返回语句。您能提供错误的行号吗?我还认为一些文本可能在错误消息中丢失了。我重新格式化了,但看起来还是有点奇怪。
void swap(struct s *p1, struct s *p2)
{
// ...
}
swap(p1,p2)
{
/* ... */
}
#include <stdio.h>
struct s {
char *st;
struct s *sp;
};
void swap(struct s *ptr1, struct s *ptr2);
int main() {
int i;
struct s *p[3];
static struct s a[]={ {"abc",a+1}, {"def",a+2}, {"ghi",a} };
for(i=0;i<3;i++) {
p[i] = a[i].sp;
}
swap(p[0], a);
printf("%s %s %s\n",p[0]->st,(*p)->st,(*p)->sp->st);
return 0;
}
void swap(struct s *ptr1, struct s *ptr2) {
char *temp;
temp = ptr1->st;
ptr1->st = ptr2->st;
ptr2->st = temp;
}