2011-08-07 44 views
0

下面的程序出現錯誤。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} 
    }; 
    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; 
} 

如何使這個程序working.Even如果我們沒有把int之前交換,我希望它會默認將它作爲int。

錯誤C4430:缺少類型說明符 - int假定。注意:C++不 支持默認int

錯誤C2078:太多的初始值設定

錯誤C2440:初始化:不能從轉換的*'到「廉政」 沒有上下文中,這種轉換是可能的

錯誤C2450:術語不計算爲服用2個參數

功能

錯誤C2456: '交換':函數式

+0

能否請您爲這些錯誤提供的行號?另外,我覺得一些文字可能會在錯誤信息已經丟失。我重新格式化,但它仍然看起來有點奇怪 –

回答

3

嘗試

void swap(struct s *p1, struct s *p2); 

void swap(struct s *p1, struct s *p2) 
{ 
    char *temp; 
    temp = p1->st; 
    p1->st = p2->st; 
    p2->st = temp; 
} 
2

swap函數不返回任何東西。在C中,這應該用void關鍵字標記(請參閱@ Dave的評論,它確實是允許的,但看起來如同您正在使用C++編譯器進行編譯時那樣不允許)。你還必須指定類型的p1p2

void swap(struct s *p1, struct s *p2); 

void swap(struct s *p1, struct s *p2) 
{ 
    // ... 
} 
+2

技術上,它沒有*有*函數,返回類型默認爲'int',而'int'函數沒有*有*返回語句。 – Dave

2
swap(p1,p2) 
{ 
    /* ... */ 
} 

這是不對的。您需要指定p1,p2作爲函數定義的一部分。即使與swap函數的前向聲明一樣。還提到它是返回類型。

1

你的程序有許多錯誤......他們中的一些,我不能正確的,因爲我不能得到什麼應該是預期的行爲...

第一件事,第一,你不需要全局聲明您要定義的函數的參數struct s *p1,*p2。其次,函數原型必須包含有問題的參數類型以及返回類型(在您的情況下爲void)。第三件事,交換功能的第一個參數是一個指向你的結構的指針,因此你需要傳遞第一個元素(一個指針指向一個

以下編譯並不會seg故障,即使我認爲其行爲是不是你所期望的一個。

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