获取数组声明错误

问题描述:

我有这个数组叫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 

请帮帮我!

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

我相信你正在寻找的是这样的:

#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