gpt4 book ai didi

c - 获取数组声明错误

转载 作者:行者123 更新时间:2023-11-30 19:22:46 24 4
gpt4 key购买 nike

我有一个名为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;
}

关于c - 获取数组声明错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15216284/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com