Use the %c conversion specifier to print a sinlge character instead of %s to print a string.
Also the memory allocation by calloc() is useless, since the pointer to char s get assigned by the address of the first element of the string literal "hello" one statement later.
#include <stdio.h>
int main (void)
{
const char *s = "hello";
printf("%c", s[2]);
return 0;
}
Output:
l
Side Note:
- Use the
const qualifier to prevent any unintentional write attempts to the string literal that lead to undefined behavior.
If you want to allocate memory and assign/initialize the allocated memory by the string literal "hello", use strcpy() (header string.h):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (void)
{
char *s = calloc(30, sizeof(*s));
if (!s) // Check if allocation failed.
{
fputs("Error at allocating memory!", stderr);
exit(1);
}
strcpy(s, "hello");
printf("%c", s[2]);
return 0;
}
Output:
l
or you can use strdup() (Note: strdup() is not part of the standard C library) which will automatically allocate memory with the string of the string literal passed as argument initialized:
#include <stdio.h>
#include <string.h>
int main (void)
{
char *s = strdup("hello");
if (!s) // Check if allocation failed.
{
fputs("Error at allocating memory!", stderr);
exit(1);
}
printf("%c", s[2]);
return 0;
}
Side note:
"The string is stored in a pointer."
Something like that is not possible. The pointer points to the first element of the string (literal). The pointer does not store a string.
calloc(memory leak). What do you mean by check each individual char ?printf("%c",s[2]);