2016-11-22 63 views
-4

我收到一個錯誤,指出我沒有太多的參數來調用'strcpy_s' 我已經查過它並找不到任何答案!感謝您的幫助提前。爲什麼我得到這個錯誤? strcpy

#include <stdio.h> 
#include <string.h> 
#define WORD_LENGTH 20 

void read_line(char str[], int n); 

int main(void) 
{ 
char smallest_word[WORD_LENGTH]; 
char largest_word[WORD_LENGTH]; 
char current_word[WORD_LENGTH]; 

printf("Enter word: "); 
read_line(current_word, WORD_LENGTH); 
strcpy_s(smallest_word, strcpy_s(largest_word, current_word)); 

while (strlen(current_word) != 4); 
{ 
    printf("Enter word: "); 
    read_line(current_word, WORD_LENGTH); 
    if (strcmp(current_word, smallest_word) < 0)strcpy_s(smallest_word, 20, current_word); 
    if (strcmp(current_word, largest_word) > 0)strcpy_s(largest_word, 20, current_word); 
} 
printf("\nSmallest word: %s \n", smallest_word); 
printf("Largest word: %s \n", largest_word); 
return 0; 
} 

void real_line(char str[], int n) 
{ 
int ch, i = 0; 
while ((ch = getchar()) != '\n') 
    if (i < n) 
     str[i++] = ch; 
str[i] = '\0'; 
} 
+1

爲'strcpy_s'簽名是'strcpy_s(字符*,爲size_t,爲const char *)',所以你需要包括'size_t'參數。 –

+0

你查了一下,但你沒有閱讀手冊頁 - 你的第一個停靠港。 –

+0

我真的不知道手冊頁是什麼。這是我第一個計算機科學課。我從來沒有聽說過它@韋瑟 – Crowe

回答

0

嘗試指定緩衝區的大小,功能不溢出:

 strcpy_s(foo, 10, bar); 

MSDN Doc

1

的strcpy和strcpy_s不具有相同的簽名。如果您沒有提供足夠大的目標緩衝區,前者將覆蓋內存,如果源字符串太大,後者將返回錯誤代碼。

檢查here

char * strcpy (char * destination, const char * source); 
errno_t strcpy_s(char *restrict dest, rsize_t destsz, const char *restrict src); 

所以,strcpy_s需要一個目標緩衝區的大小,以確保它不會溢出。

0

對於初學者來說這個功能

void real_line(char str[], int n) 
{ 
int ch, i = 0; 
while ((ch = getchar()) != '\n') 
    if (i < n) 
     str[i++] = ch; 
str[i] = '\0'; 
} 

是錯誤的。如果i退出循環後,將等於n的這個賦值語句

str[i] = '\0'; 

嘗試字符數組外面寫。

該函數可以被定義如下方式

int real_line(char s[], int n) 
{ 
    int ch, i = 0; 

    if (!(n < 1)) 
    { 
     while (i < n - 1 && (ch = getchar()) != '\n') s[i++] = ch; 
     str[i] = '\0'; 
    } 

    return i; 
} 

至於該錯誤消息,則功能strcpy_s需要三個參數,而且它不返回char *類型的指針。因此,這些陳述

strcpy_s(smallest_word, strcpy_s(largest_word, current_word)); 
//... 
if (strcmp(current_word, smallest_word) < 0)strcpy_s(smallest_word, 20, current_word); 
if (strcmp(current_word, largest_word) > 0)strcpy_s(largest_word, 20, current_word); 

}

是錯誤的。該功能strcpy_s聲明如下方式

errno_t strcpy_s(char * restrict s1, rsize_t s1max, const char * restrict s2); 

你需要的功能是什麼strcpy。在這種情況下,你確實可以寫例如

strcpy(smallest_word, strcpy(largest_word, current_word));