2013-11-20 27 views
3

爲了鍛鍊我在C語言中的編程技巧,我試圖自己編寫strncpy函數。這樣做,我一直在犯錯誤,解決他們中的大多數,最終我陷入了沒有進一步的靈感繼續下去。格式'%s'需要類型'char *'的參數

我收到的錯誤是:

ex2-1.c:29:3: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=] 
    printf("The copied string is: %s.\n", stringb); 

的事情是,它是一個非常常見的錯誤,並且它也已經在這樣描述的,只有我似乎無法申請其他人已經指出的提示出。當打印變量時,我得到的是我使用了錯誤的類型,而當我使用%d格式時,它將返回一個整數,該整數可能是第一個字符的ASCII值,因爲它在增加最大數時不會改變的字節複製。

使用GDB我已經發現,通過while循環迭代完成後,b變量保持正確的字符串,但我似乎無法打印它。

我可能缺乏關於C語言知識的非常基礎的部分,我很抱歉問這個新手問題(再次)。此外,如果您能夠提供反饋或指出我的代碼中存在其他缺陷,我將不勝感激。

#include <stdlib.h> 
#include <stdio.h> 

void strmycpy(char **a, char *b, int maxbytes) { 
    int i = 0; 
    char x = 0; 

    while(i!=maxbytes) { 
    x = a[0][i]; 
    b[i] = x; 
    i++; 
    } 

    b[i] = 0; 

} 


int main (int argc, char **argv) { 
    int maxbytes = atoi(argv[2]); 
    //char stringa; 
    char stringb; 
    if (argc!=3 || maxbytes<1) { 
     printf("Usage: strmycpy <input string> <numberofbytes>. Maxbytes has to be more than or equal to 1 and keep in mind for the NULL byte (/0).\n"); 
     exit(0); 
    } else { 

    strmycpy(&argv[1], &stringb, maxbytes); 
    printf("The copied string is: %s.\n", stringb); 

    } 

    return 0; 
} 
+2

'stringb'是'char',而不是'char *'。 – Zeta

+1

'stringb'是一個char(在傳遞給'printf()'時被提升爲int)。您需要將其聲明爲適當大小的數組。確實,「再一次」。 – 2013-11-20 23:10:53

+0

'%s'需要以nul-char結尾的字符序列的地址。您傳遞的是字符,而不是字符序列的地址,當然不是以nul-char結尾的字符。 – WhozCraig

回答

6

charchar*之間的輕微差異。第一個是單個字符,而後者是指向char(可指向可變數目的char對象)的指針。

%s格式說明確實需要一個C風格的字符串,它不僅應該是char*類型,但預計也將是空終止(見C string handling)。如果要打印單個字符,請改爲使用%c

至於程序,假設我想你要的就是你想要的東西,嘗試是這樣的:

#include <stdlib.h> 
#include <stdio.h> 
#include <assert.h> 

static void strmycpy(char *dest, const char *src, size_t n) { 
    char c; 
    while (n-- > 0) { 
     c = *src++; 
     *dest++ = c; 
     if (c == '\0') { 
      while (n-- > 0) 
       *dest++ = '\0'; 
      break; 
     } 
    } 
} 

int main(int argc, char *argv[]) { 
    size_t maxbytes; 
    char *stringb; 

    if (argc != 3 || !(maxbytes = atoll(argv[2]))) { 
     fprintf(
      stderr, 
      "Usage: strmycpy <input string> <numberofbytes>.\n" 
      "Maxbytes has to be more than or equal to 1 and keep " 
      "in mind for the null byte (\\0).\n" 
     ); 
     return EXIT_FAILURE; 
    } 

    assert(maxbytes > 0); 
    if (!(stringb = malloc(maxbytes))) { 
     fprintf(stderr, "Sorry, out of memory\n"); 
     return EXIT_FAILURE; 
    } 

    strmycpy(stringb, argv[1], maxbytes); 
    printf("The copied string is: %.*s\n", (int)maxbytes, stringb); 
    free(stringb); 

    return EXIT_SUCCESS; 
} 

但坦率地說,這是很基本的是解釋可能只是導致寫書在C上。如果你只讀了一個已經寫好的東西,那麼你會變得更好。有關C書籍和資源的清單,請參閱The Definitive C Book Guide and List

希望它有幫助。祝你好運!

+3

*輕微*? Sry基因。這讓我發笑。 – WhozCraig

+2

@WhozCraig:是的,區別只在於星號,它有多大可以是正確的:) – 2013-11-20 23:12:44

+1

差異可以忽略不計。 :P – 2013-11-20 23:13:12

相關問題