I was just printing some characters in C.
I have declared char c and assigned its characters.
then using a for loop i try to print the characters one by one.
I have used pointers, of course.
#include <stdio.h>
#include <string.h>
int main()
{
char c[4] = {"hia"};
int i;
for(i=0;i<4;i++)
{
printf(&c[i]);
}
return 0;
}
However when I compile my code using turbo, i get output "hiaiaa" instead of "hia"! What am i doing wrong here?
Your printf() call is broken. You are using the string (from the point you specify) as the formatting string. This will not print single characters. Instead each call will print from where its formatting string starts, to end of the string.
This means the first call will print all of c, the next will print from c[1] and onwards, and so on. Not at all what you wanted.
If you want to print single characters, use the %c format specifier:
printf("%c", c[i]);
No pointer necessary, since the character is passed by value to printf().
This is what happened in your loop:
0. hia
1. ia
2. a
3. \0
However, you want to print exactly one char at a time, not a null terminated string, so you should pass it as char not a char*:
printf( "%c", c[i] )
Also, you are looping four times, but string length is just three. You should use:
for( i = 0; i < strlen( c ); i++ )
...
The printf function have an char* as first argument, that's correct. However, it prints a string (that is, a zero-terminated sequence of char) so it will always do that.
If you want to print one character at a time, then you have to use that format, like in:
printf("%c\n", c[i]);
You also have another problem, and that is that you try to print the zero terminator as well. This character is not printable so will not show. Use e.g. i < strlen(c) as the loop condition to overcome this.
Also, instead of printing character-by-character, print it all as one string:
printf("%s\n", c);
1) For loop size should i<3 , not i<4 (i=3 refers to the null character at the end of the string)
2) use printf("%c",c[i]);
Explanation of what you're seeing: In each loop, printf is printing a null-terminated string. This string starts in every loop one char later inside your array.
How it should be done, depends on what you're intending. If you want to print the string char by char via pointer you may use:
char *p=&c[0];
while (*p) {
printf("%c", *p);
p++;
}
Your question is to print string using pointer. You could use
printf("%s", c);
or character by character as (include library string.h for this)
for(i=0;i<strlen(c);i++)
{
printf("%c", c[i]);
}
in C strings are stored as character arrays and are terminated by a zero-value, so called zero-terminated strings. Btw, this is why you have to make the array size of 4 for thee real chars.
In your example, you are passing pointers th each char to the printf function and printf prints the strings from your pointer to the next null-value . The 1st pass prints "hia", the 2nd ia and the 3rd a.
To print a single char in each pass, you have to use
printf ("%c", c[i]);
Your loop will call printf with the following parameter:
printf("hia"); // first loop iteration
printf("ia"); // second loop iteration
printf("a"); // third loop iteration
printf(""); // fourth loop iteration
You probably meant to print one character at a time:
for(i=0;i<3;i++) // No need to print the string termination character.
{
printf("%c", c[i]); // "%c" is the printf format code to print a single character
}
Related
I don't understand Why don’t we have to print strings in for loop ? In normal cases we need to print arrays in for loop. For example, if we want to print the array of integers. It will be like this:
int a[n];
for (i = 0; i < n; i++){
printf("%d", a[i]);
}
But for strings like:
char s[100] = " Hello ";
printf("%s\n", s);
it is enough to write the name of array.
EDIT: It seems like I didnt ask my question properly as some of you wrote answers which is not related to my question.I edit my question.
Strings terminate with the empty character '\0', that's how it is possible to know when a string ends even without explicitly passing its length.
The difference is that C-style strings (which are char arrays) are zero-terminated, whereas int arrays are normally not zero terminated.
Theoretically, you could also create an int array which is zero-terminated and print that in a loop:
int a[] = {5,7,3,0};
for (i=0;a[i]!=0;i++)
{
printf("%d",a[i])
}
However, the problem with zero-terminated int arrays is that the number 0 could be a meaningful value, so you cannot be sure that it really is the end of the array when you encounter that value. With strings, however, the ASCII-Code 0 does not represent a meaningful value, so you can be reasonably sure that you have reached the end of the string.
Your example is far from analogous. %d refers to a single integer, while %s refers to an entire (but still single) string.
You are not passing the size of the array n[] to printf either - rather you are calling printf n times. You are printing one int just as you are printing one string.
The actual string length is not known a priori, rather printf iterates the string until it encounters the \0 terminator. Equivalent to:
for( int i = 0; s[i] != '\0'; i++)
{
printf( "%c", s[i] ) ;
}
because
char s[100] = " Hello ";
is equivalent to:
char s[100] = { ' ', 'H', 'e', 'l', 'l', 'o', ' ', '\0' } ;
Strings are multiple characters all at once. You cannot ask for a specific character from a string. If you want to do so, you must refer to it as an array of chars like this
for (i = 0; i < n; i++){
printf("%c", s[i]);
}
It is because you are already providing the parameter which is "%s" to the printf function which already has a definition telling it how to print a string.
Hope it helps.
One of the reason is that char only takes 1 byte of memeory and when you just press a character, the first index of array is filled up completely and it moves on to the next one till it encounters NULL character. This is not the case with integer array where the size is more than 1 byte and is machine dependent. So you cannot escape the first index by just pressing the number less than the maximum range. If you try to do this, it will store your numbers in first index only and hence a for loop is required there.
Whenever i declare a varible as char and scan it as string "%s" my output console crashes. Here is the code
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main()
{
char a[20];
int i;
printf("Enter a name ");
scanf("%s",&a);
for(i=0;i<strlen(a);i++)
{
a[i] = toupper(a[i]);
i++;
printf("%s\n",toupper(a[i]));
}
return 0;
}
The second i++; inside the for loop body may cause the index to point off-by-one then, printf("%s\n",toupper(a[i])); will be out of bound access which invokes undefined behavior.
You can remove the i++ from inside the loop body.
Next, toupper(a[i]) returns an int, which is invalid for %s format specifier, which again invokes UB.
That said,
to prevent buffer overflow from excessive long input, it's best to limit the input length with scanf(),
You don't need to pass the address of an array, just the array name will be sufficient
So, overall, you should write
scanf("%19s",a);
You have two problems in the loop where you use toupper and print.
The first is that you increment the variable i twice in the loop.
The second problem is the printf:
printf("%s\n",toupper(a[i]));
Here you ask printf to print a string, but as argument you give it a single character (actually an int, toupper returns an int). Use the "%c" format specifier to print a single character.
By the way, you don't need to call toupper when printing, as the character should already be in upper-case because of the previous assignment.
Your printing loop is mis-behaving and giving you undefined behavior:
printf("%s\n",toupper(a[i]));
is passing toupper(a[i]) to printf()'s %s format specifier, which requires a char * not a plain char. That triggers undefined behavior.
There's no point in printing each character one by one, instead convert the entire string to upper case, then print it once:
for(i = 0; a[i] != '\0'; ++i)
{
a[i] = (char) toupper((unsigned char) a[i]);
}
printf("%s\n", a);
The casts around toupper() are sometimes needed since it takes and returns int, and you want to be a bit careful about when converting to/from characters.
Notice that I factored out the call to strlen(), this might be a bit "too clever" but it's how I would expect this code to be written. If we're going to loop over the characters, there's no need to compute the length separately.
In my program, I am making a char line[MAXLINE] and then using it in:
fgets(line, sizeof line, f);
I can then print this line with
printf("%s\n",line);
However, trying something like
printf("%s\n",line[10]);
warns me that line[10] is of type int, and something like
printf("%s\n",line + 10);
prints from character 10 onwards.
how can I just get the nth character of this string?
You can get the nth character like so:
char ch = line[10];
But you can't print it as a string, because it's not a string. Print it as a character:
printf("%c\n", line[10]);
What you are doing when you use %s in the format string in printf is printing the null-terminated string starting from the the provided pointer.
line+10 is the pointer to the 11th character in the string so it prints everything it finds in memory until it encounters /0 (null) character.
To print a single character you have to use %c in the format string.
printf("%c",line+10);
printf("%s\n",line + 10); // %s expects a char *
Instead print like this -
printf("%c\n",line + 10);
how can I just get the nth character of this string?
With strlen() function from <string.h> you can get length of string. Thus easily you can get the nth character. of the string.
The below will also work as a string in C is a char pointer to the first character. (Strings are terminated in memory with the character \0, that's how programs know where they end.)
line is a pointer to the first character and it can be advanced to the 10th character, as below (we have to advance it by 9, as no advance points to the first character).
* dereferences the pointer to get the actual value.
#include <stdio.h>
int main()
{
char line[] = "abcdefghijkl";
printf("%c\n", *(line+9));
return 0;
}
I have a very simple program to print the chars in a string but for some reason it is not working:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void * print_chars(char *process_string) {
int i;
int string_len;
string_len = strlen(process_string);
printf("String is %s, and its length is %d", process_string, string_len);
for(i = 0; i < string_len; i++) {
printf(process_string[i]);
}
printf("\n");
}
int main(void) {
char *process_string;
process_string = "This is the parent process.";
print_chars(process_string);
return 0;
}
When I run it in Netbeans, I get the following:
RUN FAILED (exit value 1, total time: 98ms)
If I remove the line
printf(process_string[i]);
the program runs but nothing prints out to the console (obviously).
Any ideas what I'm missing here?
You need a format in the line
printf(process_string[i]);
i.e.
printf("%c", process_string[i]);
There are a couple of problems.
One is that you're not seeing any output from the printf("String is %s, and its length is %d", ...). This is because standard output is line buffered by default, and you are not including a newline, so it never actually decides that there's a line ready to print. If you change the format string to add a \n, you will see the output from this command.
The second is that you are passing a char into the first argument of printf(), where it expects a char *. This causes it to crash, as it tries to interpret that character as a pointer. You want to pass something like printf(process_string) instead. However, it's generally a bad idea to pass a variable string directly into the first argument of printf(); instead, you should pass a format string that includes %s, and pass the string in as the corresponding argument: printf("%s\n", process_string). Or, if you want to print it character by character, printf("%c", process_string[i]), followed by a printf("\n") to flush the buffer and actually see the output. Or if you're doing it character by character, putchar(process_string[i]) will be simpler than printf().
printf() expects, as first parameter, a pointer to char. What you are passing is a char, not a pointer to one.
Anyway, printf() is not the function to use here. Try putc()...
I have a string I composed using memcpy() that (when expanded) looks like this:
char* str = "AAAA\x00\x00\x00...\x11\x11\x11\x11\x00\x00...";
I would like to print every character in the string, and if the character is null, print out "(null)" as a substitute for '\0'.
If I use a function like puts() or printf() it will just end at the first null and print out
AAAA
So how can I get it to print out the actual word "(null)" without it interpreting it as the end of the string?
You have to do that mapping yourself. If you want to, that is. In C, strings are null-terminated. So, if you use a formatted output function such as printf or puts and ask it to print a string (via the format specifier %s) it'd stop printing str as soon as it hits the first null. There is no null word in C. If you know exactly how many characters you have in str you might as well loop over them and print the characters out individually, substituting the 0 by your chosen mnemonic.
The draft says 7.21.6.1/8:
p The argument shall be a pointer to void. The value of the pointer is
converted to a sequence of printing characters, in an
implementation-defined manner.
However, the following:
$ cat null.c
#include <stdio.h>
int main() {
printf("%p\n", (void *)0);
}
produces:
00000000
on both gcc 4.6 and clang 3.2.
However, on digging deeper:
$ cat null.c
#include <stdio.h>
int main() {
printf("%s\n", (void *)0);
}
does indeed produce the desired output:
(null)
on both gcc and clang.
Note that the standard does not mandate this:
s If no l length modifier is present, the argument shall be a pointer
to the initial element of an array of character type.280) Characters
from the array are written up to (but not including) the terminating
null character. If the precision is specified, no more than that many
bytes are written. If the precision is not specified or is greater
than the size of the array, the array shall contain a null character.
Relying on this behavior may lead to surprises!
Instead of printing the string with %s , you will have to come up with a for loop that checks a condition whther a given char in your char array is a \0 and then print the NULL
From C++ Reference on puts() (emphasis mine):
Writes the C string pointed by str to stdout and appends a newline
character ('\n'). The function begins copying from the address
specified (str) until it reaches the terminating null character
('\0'). This final null-character is not copied to stdout.
To process data such as you have, you'll need to know the length. From there, you can simply loop across the characters:
/* ugly example */
char* str = "AAAA\x00\x00\x00...\x11\x11\x11\x11\x00\x00...";
int len = ...; /* get the len somehow or know ahead of time */
for(int i = 0; i < len; ++i) {
if('\0' == str[i]) {
printf(" (null) ");
} else {
printf(" %c ", str[i]);
}
}
One of the key cornerstones of C is strings are terminated by '\0'. Everyone lives by that rule. so I suggest you not think of your string as a string but as an array of characters.
If you traverse the array and test for '\0', you can print "(null)" out in place of the character. Here is an example. Please note, your char * str was created either as a char array or on the stack using malloc. This code needs to know the actual buffer size.
char* str = "AAAA\x00\x00\x00...\x11\x11\x11\x11\x00\x00...";
int iStrSz = <str's actual buffer size>
int idx;
for(idx=0; idx<iStrSz; idx++)
{
if('\0' == *(str + idx)
{
sprintf("%s", "(null)");
}
else
{
putchar(*(str + idx));
}
}
printf("%s", "\n");