arrays - How to store string from an array of strings in to a variable in C
问题描述
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
char movie[15];
char movielist[25][30]={"thalaiva","aruvi","sarkar","visvasam","veeram","mersal","bigil","kaithi","mahanadhi","papanasam","vishwaroopam","padayappa","thadam","indian","petta","kaala","psycho","comali","bahubali","saaho","enthiran","vettai","asuraguru","penguin","cocktai"};
movie=movielist[rand()%25];
printf("%s",movie);
}
I want the variable movie to store any random string from the array movielist! The code above gives me error. main.c:8:7: error: assignment to expression with array type movie=movielist[rand()%25];
解决方案
Your code has two main issues.
1.
With
movie = movielist[rand() % 25];
you attempt to assign movie
(an array of 15 char
, type char [15]
) by a pointer to an array of 30 char
(type char (*)[30]
). This is not permissible in C. You cannot assign arrays.
Since you don't want to modify/change the movie titles/strings in the program, you don't need a two-dimensional array for movielist
and an array for movie
.
Use an array of pointer for movielist
which point to string literals and a pointer for movie
instead.
The pointer move
you assign then by the value of one of the pointers in movielist
.
2.
rand()
needs a seed with srand()
. Without that, rand()
won't work properly. But you forgot that in your code.
A usual way is to provide a seed dependent upon the CPU clock time.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h> // for the time seed.
int main (void)
{
char const * movie;
char const * const movielist[] = {
"thalaiva","aruvi","sarkar","visvasam","veeram",
"mersal","bigil","kaithi","mahanadhi","papanasam",
"vishwaroopam","padayappa","thadam","indian",
"petta","kaala","psycho","comali","bahubali",
"saaho","enthiran","vettai","asuraguru","penguin",
"cocktai"
};
// initialize random seed.
srand(time(NULL));
movie = movielist[rand() % 25];
printf("%s", movie);
}
Side note:
void main()
is not compliant to the C standard. Useint main (void)
.
推荐阅读
- python-3.x - 我收到此错误错误:当我尝试在我部署在 gcp 中的 streamlit 网站中上传图像时,请求失败,状态码为 400
- django - Django Admin 无法在具有多个外键的模型中显示属性到另一个模型
- .net - 具有众多身份角色的 .NET 5 400 错误
- visual-studio-code - pickProcess 命令的源代码 VS Code
- r - 删除数据框中所有列名的字符
- reactjs - 从 Material UI 下拉选择中显示模态
- javascript - 只有当我在 Spotify API 上发出第一次获取请求(单击搜索方法)时,我才会得到 401,之后就可以正常工作了。请帮我解决它
- python - Python .loc 返回一个 TypeError
- julia - 如何在 Colab 上打开 .ipynb 笔记本
- javascript - 使用useState在React中更新数组时如何保留以前的值