Reputation:
I want this array to print all the elements in this code but it doesn't.
#include <stdio.h>
#include <stdlib.h>
//#include "student_info.h"
int main()
{
char animals[3];
animals[0] = "lion";
animals[1] = "Cat";
numbers[2] = "Tiger";
printf("%s", numbers[2]);
}
Upvotes: 0
Views: 369
Reputation: 11209
You should have declared an array of array of char. What you have is an array of char that hold an individual character each.
const char *animals[3];
animals[0] = "Lion";
animals[1] = "Tiger";
animals[2] = "Wolf";
Another way to do it is:
char animals[3][10] = {
"Lion",
"Tiger",
"Wolf"
};
Working demo of both approaches:
#include <stdio.h>
int main() {
const char *animals1[3];
animals1[0] = "Lion";
animals1[1] = "Tiger";
animals1[2] = "Wolf";
for (int i=0; i<3; i++)
printf("%s\n", animals1[i]);
char animals2[3][10] = {
"Lion",
"Tiger",
"Wolf"
};
for (int i=0; i<3; i++)
printf("%s\n", animals2[i]);
}
See Online Demo
Upvotes: 1
Reputation: 26763
Assuming numbers
-> animals
....
You declare an array of three single char
s. char animals[3];
Then you attempt to write "strings" (there actually is no such thing in C) to places where only single chars are possible. animals[0] = "lion";
And you should get lots of warnings like
main.c:7:16: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
animals[0] = "lion";
Reading compiler warnings closely and treating them as errors is a habit I recommend adopting.
This one means that "lion"
is a pointer to an (unchangeable) 0-terminated sequence of char
s in memory. And you are trying to write that pointer into basically a char
variable, where char
is one of the types which for the compiler is a narrow integer.
Your code makes some sense if you change your array to store pointer to characters.
char* animals[3];
That matches how you init it and how you print it, with "%s"
which is for pointers to 0-terminated sequences of characters, the closest thing C has to strings.
That code (remember the numbers...) gets you no warnings here
https://www.tutorialspoint.com/compile_c_online.php
and an output of:
Tiger
For your goal to print all entries in the array you need to understand that C does not have inbuilt support of printf()
for arrys of "strings" (it "barely" manages char-sequences...).
So you will have to implement a loop yourself. That also gives you control over how it prints, one string per line, all in one line, what in between...
Upvotes: 2