2016-12-07 23 views
-2

我正在編寫一些C,其中程序將把第一個命令行參數轉換爲int並檢查它是否爲int。如果它不是一個整數值,它將嘗試檢查字符串是否以'。'開頭。性格與否。出於某種原因,我得到一個未定義的參考。
當它看起來被定義時,這是一個未定義的引用?對'startswith'的未定義引用

這裏是下面的代碼:

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 
#include <ctype.h> 
#include <string.h> 
int startswith(char,char); 

int main(int argc, char * argv[]) { 
    int forst; 
    srand(time(NULL)); 
    int speed_delay = rand() % 20; 
    printf("The speed delay is:%i\n", speed_delay); 
    int first = atoi(argv[1]); 
    printf("First:%i\n", first); 

    if (first == 0) { 
     //this means text was inserted instead of a number 
     if (startswith(first, '.')) { 
      printf("string starts with a period !"); 

     } 
    } else { 

    } 

    int startswith(const char * one, 
     const char * two) { 
     if (strncmp(one, two, strlen(two)) == 0) { 
      return 1; 
     } 
     return 0; 
    } 
} 
+3

你的函數聲明不符合你的定義。 '(char,char)'與'(const char *,const char *)'不一樣。而'first'是一個'int',所以你將無法將它傳遞給任何一個版本。 – yano

+3

打開您的編譯器警告。也要關注他們。 – pmg

回答

1

你的宣言和startswith定義是不相容的。

聲明有char類型的兩個參數,但函數實際上有兩個參數,類型爲const char *

您還定義了startswith內的main。函數不能嵌套。

因爲沒有匹配聲明的函數,所以你有一個未定義的引用。

修復您的聲明以符合定義。

int startswith(const char *, const char *); 

您也沒有正確調用此函數。你通過一個int和一個char。它應該被稱爲是這樣的:

if(startswith(argv[1],"."))