2013-03-05 63 views
-1

我有這個數組叫arr_[6],有一個想法包括六個字符串......但是當我聲明這個數組編譯器會拋出錯誤。獲取數組聲明錯誤

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

int main() 
{ 
    int i; 

    char arr_1[]= {"My_name","your Name", "His Name"}; 


    char *arr_p; 

    arr_p = malloc(sizeof(char)*6); 

    arr_p = arr_1; 

    printf("%s\n",*arr_p); 


    system("PAUSE"); 

    return 0; 
} 

顯示的錯誤如下:

> main.c: In function `main': main.c:9: error: excess elements in char 
> array initializer main.c:9: error: (near initialization for `arr_1') 
> main.c:9: error: excess elements in char array initializer main.c:9: 
> error: (near initialization for `arr_1') 
> 
> make.exe: *** [main.o] Error 1 

請幫幫我!

回答

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

int main() 
{ 
    int i; 
    const char *arr_1[]= {"My_name","your Name", "His Name"}; // has to be an array of <char *> 

    //arr_p is not necessary 

    printf("%s\n",*arr_1); // will print the first string, "My_name" 
    printf("%s\n",arr_1[1]); // will print the second string, "your Name" 
    printf("%s\n",arr_1[2]); // will print the third string, "His Name" 
    system("PAUSE"); 
    return 0; 
} 
0

我相信你正在尋找的是這樣的:

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


int main() 
{ 
    int i; 
    char* arr_1[]= {"My_name","your Name", "His Name", NULL}; 
    char** arr_p; 

    arr_p = arr_1; 

    i = 0; 
    while (arr_p[i] != NULL) 
    { 
     printf("%s\n",(arr_p[i])); 
     ++i; 
    } 

    system("PAUSE"); 
    return 0; 
} 

這是我修改的列表:

  1. 使用char* arr_1[]聲明字符串數組因爲每個字符串都是一個字符數組。
  2. 如果你需要一個指向一個char *,你需要聲明的指針是數據類型的char**
  3. 二手NULL作爲數組中的最後一個元素,讓你知道當你已經達到的結束字符串數組。使用while循環遍歷所有字符串。
+0

謝謝我的朋友......我實際上只是爲此而努力......我感謝您的努力......謝謝! – EmbeddedCrazy 2013-03-05 06:02:33