首页 > 解决方案 > 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];

标签: arrayscstring

解决方案


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. Use int main (void).

推荐阅读