I would like to pass a character pointer ( to an array) to a function which will print the letters one by one. For example I am using the code below:
#include<stdio.h>
#include<string.h>
void string1(char *q)
{
while(*q)
{
printf(q++);
printf("\n");
}
}
main()
{
char name[]= "hello";
char *p=name;
string1(p);
}
which prints:
hello
ello
llo
lo
o
But I want it to print;
h
e
l
l
o
I am unable to do it by using the variable q inside printf. Thanks
Your sentence: printf(q++); is wrong.
You have to print a character, only:
printf("%c", *g++);
A better option:
putchar(*g++);
In general, take in account that:
g is the adress of an array of characters.
To access the first character pointed by g, it is necessary to use the operator *, this way: *g.
The modifier "%c" in printf() gives you the possibility of printing a datum of type char.
You should always use a format string with printf. Passing strings with unknown values into the printf function can result in an uncontrolled format string vulnerability. Printing a c-string with printf should be done like this: printf("%s", string_pointer);
That said, to print one character at a time you can use the %c formatter:
while(*q) {
printf("%c\n", *(q++));
}
You need to specify the first argument of printf()
By doing this:
printf(q++);
The application is behaving as if you want to print a string (because it keeps printing until it reaches \0), so what you are doing is equivalent to this;
printf("%s",q++);
But what you actually want is printing only the char at position q:
printf("%c",q++); // Prints only the char at q, then increment q
Related
int main(){
printf("hello world"+2);
}
test.c:32:25: warning: adding 'int' to a string does not append to the string
[-Wstring-plus-int]
printf("hello world"+2);
~~~~~~~~~~~~~^~
test.c:32:25: note: use array indexing to silence this warning
printf("hello world"+2);
^
& [ ]
1 warning generated.
alpha#Desktop % ./a.out
llo world%
So this is what I am getting. And if I increase the number then it is simply slicing the string by that.Can anyone explain this output and why it's happening to me?
In the C and C++ languages, every string that has been defined with double quotes is of type char* (pointer to char) as a statically allocated char array. When you call printf() on such string it does something like this:
void printf(char* str) {
while(*str!= '\0') {
// write the current character to stdout
write(STDOUT_FILENO, str, sizeof(char));
str ++;
}
}
I don't know if it really is written that way, indeed it probably isn't, the functionality is the same. It iterates over the string until it finds the null-terminator ('\0'). All pointers are almost equivalent to long and when you add a number to them, it increments their underlying value with sizeof(type), where type is the type of value the pointer points towards. Thus, when you add a number to "Hello World", makes printf() think your string starts on a different memory address and prints 'llo World'.
If you want to print the string with the value '2' appended to the end of it, as #Elliott Frisch stated, you would use print("Hello World%d", 2).
I would suggest looking at sprintf() and strcat() for string concatenation in C.
In C, what we might think of as a string is actually an array of characters. What you pass to printf() in both cases is a pointer to the start of such an array. You can do arithmetic with pointers, which is what you are doing here.
Here's some clarification.
#include <stdio.h>
int main(void) {
// A
printf("Hello, world!\n");
// B
printf("Hello, world!\n" + 2);
}
Output:
Hello, world!
llo, world!
In case A, you point to the start of an array containing the H character, and it reads until the last one (which is in fact a 'this is the end'-character: \0).
⬇️
H
e
l
l
o
,
w
o
r
l
d
!
\n
\0
In case B, you add 2 to the pointer before passing it to printf(). Now printf() starts reading here:
⬇️
H
e
l
l
o
,
w
o
r
l
d
!
\n
\0
This is what causes your 'slice'.
I have written this code where I want to add two integers, two doubles and concatenate two strings out of which one of the integer, double and the string is already declared and the other integer, string and double are to be taken by the user. But it seems that the program isn't taking another string as an input.
I have written a similar program where I can take the string from the user using scanf but the same isn't working here.
int main() {
int i = 4;
double d = 4.0;
char s[] = "My college name is ";
// Declare second integer, double, and String variables.
int i2,sum1;
double d2,sum2;
char s2[100];
// Read and save an integer, double, and String to your variables.
scanf("%d",&i2);
scanf("%lf",&d2);
scanf("%[^\n]%*c",&s2);
sum1= i+i2;
sum2= d+d2;
strcat(s,s2);
// Print the sum of both integer variables on a new line.
printf("%d\n",sum1);
printf("%.1lf\n",sum2);
printf("%s",s);
return 0;}
After I made the necessary changes like removing & from s2 and changing s[] to s[200], I still cannot get the concatenated string. I am writing my edited code. Kindly help me with that.
int main() {
int i = 4;
double d = 4.0;
char s[200] = "My college name is ";
// Declare second integer, double, and String variables.
int i2,sum1;
double d2,sum2;
char s2[100];
// Read and save an integer, double, and String to your variables.
scanf("%d",&i2);
scanf("%lf",&d2);
scanf("% [^\n]%*c",s2);
sum1= i+i2;
sum2= d+d2;
strcat(s,s2);
// Print the sum of both integer variables on a new line.
printf("%d\n",sum1);
printf("%.1lf\n",sum2);
printf("%s",s);
return 0;
}
Kindly help me with the bug here.
It's not taking your string input because you use %[^\n]%*c to scan the string. which instuct the program to return after geting a newline as input. And the string got a newline form the buffer after scanning d2, and return with out taking further input.
To get rid of this you need to input a char before taking the input of the string. Change the following lines:
scanf("%lf",&d2);
scanf("%[^\n]%*c",&s2);
To:
scanf("%lf",&d2);
getchar();
scanf("%[^\n]%*c",&s2);
And your code will take the string input properly.
Additionally, you can also do this (taking a extra character input befor string input) by putting a extra space before % sign.
Changing the following line:
scanf("%[^\n]%*c",&s2);
To:
scanf(" %[^\n]%*c",&s2);
Also do the same thing.
You are passing the wrong type of argument to scanf. s2 is an array of chars, so &s2 is a pointer to an array of chars, not a pointer to a char.
(You also ought to have bounds checking to prevent array overflows, add a newline to your final printf, etc. But eliminating the & will make your program compile and run)
Possibly your use of
scanf("%[^\n]%*c",&s2);
As far as I'm aware you can use
scanf("%[^\n]%*c",s2);
or
scanf("%[^\n]%*c",&s2[0]);
As the variable s2 is itself a pointer to the first memory address of the array, using &s2 is just a pointer to a pointer and has no allocated consecutive memory addresses to fill. Hope this helps.
Replace:
scanf("%[^\n]%*c",&s2);
With:
fgetc(stdin);
fgets(s2, 100,stdin);
:)
I'm trying to beat string pointers in c, so I write this code but I didn't get the result that I expected.
I'm creating a string variable, and I want to pass it to a function that check if the string lenght is bigger than 10.
This is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
bool is_bigger_than_10(char *);
int main()
{
char *string1 = "";
int i = 0;
printf("Initial string: %s\n",&string1);
printf("Size is: %d\n",strlen(&string1));
printf("Give me one string: ");
scanf("%[^\t\n]s",&string1); //This scan allows me to enter string with spaces
printf("You write: %s\n", &string1);
printf("Size is: %d\n",strlen(&string1));
printf("String character by character:\n");
for(i = 0; i < strlen(&string1) ; i++)
{
printf("%c ",&string1[i]);
}
printf("\nNow let's check if it's bigger than 10\n");
printf("Answer is: %d",is_bigger_than_10(&string1));
return 0;
}
bool is_bigger_than_10(char *textx)
{
printf("%s --> %d > %d\n",&textx, strlen(&textx),10);
if(strlen(&textx) > 10)
{
return true;
}
else
{
return false;
}
}
The expected output should be:
Initial string:
Size is 0:
Give me one string: axel
You write: axel
String character by character:
a x e l
Now let's check if it's bigger than 10
a x e l --> 4 > 10
Answer is: 0
If yoy run that code and enter axel as the input string you will get this:
Initial string: $0#
Size is 3:
Give me one string: axel
You write: axel
String character by character: a b c d e
a x e l
Now let's check if it's bigger than 10
' --> 3 > 10
Answer is: 0
It's kind of weird, could some one help me to correct this code?
There are two things going on here:
First, your char pointer needs to point somewhere. With the line
char *string1 = "";
you create a pointer to a string literal, which you can't write to. (Obviously you can, given your output, but you just got lucky on a system that allows it.) Create a character buffer instead:
char string1[200] = "";
and ideally enforce the constant buffer limit when you read the string.
Second, you don't need all these &s. The & is not a magic marker that you have to prepend to all your arguments.
The & takes the address of a variable and passes it as a pointer. You need that when the called function needs to change the variable via the pointer. Printing doesn't need to change anything, so unless you want to print the address of a variable with %p, you shouldn't pass addresses. (In the special case of your program, you can just remove all ampersands with search and replace.)
When scanning, you need to change variables if you convert input to numbers or if you scan a char. The exception is when you scan strings with %sor %[...]: Here, you pass a char buffer (as a pointer to its first elements) and the function then fills that buffer.
The problem with scanf and printf is that the arguments after the format string are variadic, which means they will accept any arguments without type checking. The good thing is that most compilers can tell whether a format string matches the arguments and will issue warnings, it you enable them. Do yourself a favour and do that.
(Warnings will also tell you that you have type mismatches in functions where the type of the argument is known, such as your is_bigger_than_10.)
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
}
#include <stdio.h>
#include <string.h>
void main()
{
char array[]="hello";
printf("%s",array[0]);
printf("%c",array[0]);
}
couldn't able to access array[0] when %s is used but able to access array[0] when %c is used, help me to find a solution for this.
you should use address while using with %s ==> &array[0]
because %s requires a pointer as argument.
usually we use
printf("%s",character_array_name);
here character_array_name is the address of first element
character_array_name == &character_array_name[0];
and if you want to print only one character , you need to use
printf("%.1s",character_array_name);
Example Code:
#include<stdio.h>
int main()
{
char *str="Hello World";
printf("%s\n",str); //this prints entire string and will not modify the pointer location but prints till the occurence of Null.
printf("%.1s\n",str); //only one character will be printed
printf("%.2s\n",str); //only two characters will be printed
//initially str points to H in the "Hello World" string, now if you increment str location
str++; //try this str=str+3;
printf("%.1s\n",str); //only one character
printf("%.2s\n",str); //only two characters will be printed
str=str+5; //prints from the W
printf("%s\n",str); //this prints upto Hello because scanf treats space or null as end of strings
printf("%.1s\n",str); //only one character
printf("%.2s\n",str); //only two characters will be printed
return 0;
}
Although you have accepted an answer , I thought my answer could help you in a certain way.
String literals are a sequence of characters and you can visualize your array like this :
+---+---+---+---+---+----+
array: | h | e | l | l | o | \0 |
+---+---+---+---+---+---+-
^
|
array[0]
printf is a variadic function and it doesn't know anything about its arguments until you specify them , so when it sees %c format specifier it assumes that the next argument will be a variable storing a character ,in this case its array[0] that is the character h is stored at the index 0 of the array .
Now, when printf sees a %s it assumes that the next argument will be a pointer pointing the string literal ("hello") that you want it to print , in this case array[0] is not a pointer, you should put array instead in the printf , please note that array names are not pointers but array name decays to pointer
Besides , you should use int main(void) in place of void main its standard