• Register
1 vote
315 views

Problem:

I am getting the following error :

error: array initializer must be an initializer list or string literal

For the array;

char x[80] = GetString();  

Can any body explain or help?

10 7 2
6,050 points

1 Answer

1 vote

Answer:

First, when declaring a char array, you've to specify its size within the brackets like:

char arr[10]; or char arr[20];
except when you're initializing it with a string literal.

And since we don't know the number of characters the user will enter beforehand which we may consider that GetString() takes care of that and returns a string (a char *). You may just declare a string and assign GetString() to it like that:

string x = GetString();
then access the contents of that string like you'd do with a char array. For example, if I wanna print out the first char in that string I may have something like this:

printf("%c\n", x[0]);
by assuming you're using a char array for any reason, you don't have to cast the char you're accessing to a char since it's already a char

And a secoend way to initialize is:

char arr[7];

arr[0] = 'k';
arr[1] = 'a';
arr[2] = 'm';
arr[3] = 'r';
arr[4] = 'u';
arr[5] = 'l';
arr[6] = '\0';

 

11 6 4
34,930 points

Related questions

1 vote
1 answer 26 views
26 views
Problem: I am beginner in pyhton prgramming language, I tried to convert string array to int array using python so I wrote a code which contains- testing_list = ['4', '2', '3', '9', '5'] And my code is: testing_list = ['4', '2', '3', '9', '5 ... list is : str(testing_list) Converted list is : str(testing_list) why am I not getting the converted result and what is the way to get the acurate result?
asked Mar 29 LizzyM 6.1k points
0 votes
1 answer 12 views
12 views
I am new to python programming.. I was trying to check if a string is empty or whitespace in a code : Mystr= "" Yourstr = " " print ("This string is empty : ", end = "") if(not Yourstr): print ("Yes") print ("This string is empty : ", end = "") if(not Mystr): print ("No") It’s output is : This string is empty : This string is empty : No Its not giving me actual result what can I do now?
asked Mar 16 LizzyM 6.1k points
1 vote
1 answer 15 views
15 views
Problem: I was tring to find the length of a string in python. So I wrote a code: string = 0 for c in "popular": string+==1 print (string) which gives following error; File "ab.py", line 3 string+==1 ^ SyntaxError: invalid syntax Is this the right way to do this or there are other waysto find this out?
asked Mar 28 LizzyM 6.1k points