Reverse an input character string - c

I would like to reverse an input character string and I use the the pointer which points to the last character and make it print the string while the pointer address decreases. However, I could not get the whole string. Could anyone tell me what is wrong?
//Reverse a charater string
#include<stdio.h>
int main()
{
char a[50];
int l;
int *p;
printf("Please input a character string:\n");
scanf("%s",a);
l = strlen(a);
for (p = &a[l-1]; p >= a; p--)
{
printf("%c",*p);
}
printf("\n");
return 0;
}
Output:
Please input a character string:
asdfasdfasdf
fff

You have declared p as integer pointer. It should be a char pointer.
int *p;
should be
char *p;

The problem is the use of the int type for *p.
Since an int on your system is 32 bits wide (four times bigger than a char which is 8 bits on your system), when the pointer is being decremented, it is printing out every fourth character in the reverse of the string.
So, with your sample string, asdfasdfasdf, the pointer points to the last f, then the middle f, then the first f.
Similar example:
Please input a character string:
abcdefghijklmno
l is 15, a[l-1] is o
okgc
Press any key to continue . . .
If you change your pointer to the char type it will decrement properly, pointing to every character in the string in reverse order.

When you increment/decrement a pointer of type T*, the address contained in it changes by sizeof(T). Since you have declared p to be int*, the pointer address changes by sizeof(int). On your machine sizeof(int) == 4*sizeof(char), explaining the result you see. Change the type of p to char*.

Related

C pointer question (main versus function parameters)

I am really struggling with pointers in C. Specifically, I have been having trouble understanding how to work with pointers when they are in main versus when I input a pointer into a function parameter from main.
I have a few scenario questions about them that hopefully someone can answer:
int main (int argc, char* argv[]) {
int x = 7;
int* num = 4;
char* word = "johnny";
//Q1. how do I get the address of 'num'?
//Q2. how do I get the address of 'x'? (should I be using x's or num's address?)
//Q2. how do I get the value of 'num'?
//Q3. how do I get the address of 'word'?
//Q4. how do I get the whole string for 'word'?
//Q5. how do I get an individual character in 'word'? (for index 0 ('j') and index 3 ('n'))
}
bool some_func (int* count, char** name) {
//Q6. how do I get the address of the inputted 'count'?
//Q7. how do I get the value of the inputted 'count'?
//Q8. how do I get the address of the inputted string 'name'?
//Q9. how do I get the whole string of the inputted string 'name'?
//Q10. how do I get an individual character of the inputted string 'name'? (for index 0 ('j') and index 3 ('n'))
}
For my recent homework assignments, I've been given intimidating headers like these and I don't know how to get the values that I want out of them. Say I found out that saying '*name' got me the whole string, where do I go from there?
If someone could answer all of the questions in the code I think that would probably be the best way of learning it since it's through example. Thanks!
Firstly, when you declare int* num, you created a pointer. You cannot assign a value directly to a pointer. What you could do is declare a variable, like you did for int x, and point the pointer to variable x (hence the name pointer) by using num = &x (&x refers to address of x, and is assigned to num) To get the value of num, you will have to use *num. Below is an example:
int *num;
int a = 4;
num = &a;
printf("address of a is %p, and value of a is %d", num, *num);
Output to first example:
address of a is <0xsome address> , and value of a is 4
As for characters, same thing you can't assign a value directly to pointer (like you did in char* word = "johnny";. A concept I think you should know is that "johnny" is a String, and strings are essentially an array of characters, hence each character of the string has its own address. Using similar to previous example:
char* word;
char someString[6] = "johnny";
word = &someString[0];
printf("address of first char of someString is %p, 1st char of someString is %c, 2nd char of someString is %c", word, *(word), *(word+1));
Output for the second example:
address of first char of someString is <0xsome address>, 1st char of someString is j, 2nd char of someString is o
Importing thing to note is that when accessing each character of the string using de-referencing of pointers, the +n must be inside the bracket with the pointer word.
*word+1 //WRONG
*(word+1) //CORRECT
Hope this gives you a base foundation of what you will need to tackle the rest of the questions!

Weird beahaviour of string pointers

#include <stdio.h>
int main()
{
char*m ;
m="srm";
printf("%d",*m);
return 0;
}
The output is 115. Can someone explain why it gives 115 as output?
*m is the same as m[0], i.e. the first element of the array pointed to by m which is the character 's'.
By using the %d format specifier, you're printing the given argument as an integer. The ASCII value of 's' is 115, which is why you get that value.
If you want to print the string, use the %s format specifier (which expects a char * argument) instead and pass the pointer m.
printf("%s\n", m);
You have a few problems here,
the first one is that you're trying to add three bytes to a char, a char is one byte.
the second problem is that char *m is a pointer to an address and is not a modifiable lvalue. The only time you should use pointers is when you are trying to point to data
example:
char byte = "A"; //WRONG
char byte = 0x61; //OK
char byte = 'A'; //OK
//notice that when setting char byte = "A" you will recieve an error,
//the double quotations is for character arrays where as single quotes,
// are used to identify a char
enter code here
char str[] = "ABCDEF";
char *m = str;
printf("%02x", *m); //you are pointing to str[0]
printf("%02x", *m[1]); //you are pointing to str[1]
printf("%02x", *m[1]); //you are pointing to str[1]
printf("%02x", *(m + 1)); //you are still pointing to str[1]
//m is a pointer to the address in memory calling it like
// *m[1] or *(m + 1) is saying address + one byte
//these examples are the same as calling (more or less)
printf("%02x", str[0]); or
printf("%02x", str[1]);
Pointers and arrays act similarly .Array names are also pointers pointing to the first element of the array.
You have stored "srm" as a character array with m pointing to the first element.
"%d" will give you the ASCII value of the item being pointed by the pointer.
ASCII value of "s" is 115.
if you increment your pointer (m++) then print it's ascii value , output will be ascii value of "r" - 114.
#include <stdio.h>
int main()
{
char *m ;
m="srm";
m++; //pointing to the 2nd element of the array
printf("%d",*m); //output = 114
return 0;
}

why printf is not showing string on removing & and not showing address in C?

#include<stdio.h>
void main(){
char *r;
printf("Enter the string : ");
scanf("%s",&r);
printf("\nThe string is : %s",&r);
}
i am using DEV C++ (tdm-gcc 4.9.2 64-bit release)
in printf statment & removal will lead to printing of string but it is showing no output which confuses me alot
and i read that we can also use scan without & in case of string but it also not working in C
There is a big difference between char buf[64] and char *buf.
I suggest you to know the difference by printing sizeof those two declarations.
EX:
char *r;
char buf[64];
printf(" Size of array :%d pointer :%d\n", sizeof(buf), sizeof(r));
char *r; is pure declaration of a pointer which hold address of a char type variable.
char *r is char pointer, and right now it is pointing to junk value.
char buf[64], is char buffer of 64 bytes and buf is pointing to the first character.
char *r is pointing unknown/junk value. Before using this kind of approach, you should allocate memory.
char *r = (char *) malloc(32);
or
char buf[64];
char *r;
r = buf;
---> Now 'r' is pointing to buf, which already has memory allocated.
Now, you can understand the difference.
The %s format specifier to scanf expect a pointer to the first element of an array of char. In other words, a char *. You are instead passing a char **. Using the wrong format specifier invokes undefined behavior.
Define r as an array:
char r[100];
Then you can pass r to scanf, which decays into a pointer to the first element:
scanf("%99s", r);
Note also that we specify a maximum length here so that there is no risk of writing past the end of the array if too many characters are entered.
Similarly with printf, you need to call it as follows:
printf("\nThe string is : %s",r);

How to use a pointer to point only at half of an array

I'm new to C and pointers, so i have this problem. I want to tell to pointer how much memory it should point to.
char * pointer;
char arr[] = "Hello";
pointer = arr;
printf("%s \n", pointer);
This pointer will point to whole array, so i will get "Hello" on the screen. My question is how can i make pointer to only get "Hel".
You may try this:
char * pointer;
char arr[] = "Hello";
pointer = arr;
pointer[3] = '\0'; // null terminate of string
printf("%s \n", pointer);
If you always work with strings, then have a look at strlen for getting length of a string. If a string arr has length l, then you may set arr[l/2] = '\0', so that when you print arr, only its first half will be shown.
You may also want to print the last half of your string arr? You can use pointer to point to any place you want as the start. Back to your example, you may try:
char * pointer;
char arr[] = "Hello";
pointer = arr + 2; // point to arr[2]
printf("%s \n", pointer);
Have a check what you will get.
printf has the ability to print less than the full string, using the precision value in the format string. For a fixed number of characters (e.g. 3), it's as simple as
printf( "%.3s\n", pointer );
For a variable number of characters, use an asterisk for the precision, and pass the length before the pointer
int length = 3;
printf( "%.*s\n", length, pointer );
You don't know what a pointer is so I'll explain.
A pointer does not point to a string. It points to a char! Yes, a char. A string in C is really just a set of chars all one after the other in the memory.
A char* pointer points to the beginning of a string. The string ends when there is a '\0' (aka null) char. When you printf("%s",s), what printf does is a cycle like this:
int i;
for(i=0;1;i++) //infinite cycle
{
if(s[i]=='\0')
break;
printf("%c",s[i]);
}
Meaning it will not print a string but all the chars in a char array until it finds a null char or it goes into memory space that is not reserved to it (Segmentation fault).
To print just the 1st 3 characters you could do something like this:
void printString(char* s,int n) //n=number of characters you want to print
{
if(n>strlen(s))
n=strlen(s);
else if(n<0)
return;
char temp=s[n]; //save the character that is in the n'th position of s (counting since 0) so you can restore it later
s[n]='\0'; //put a '\0' where you want the printf to stop printing
printf("%s",s); //print the string until getting to the '\0' that you just put there
s[n]=temp; //restore the character that was there so you don't alter the string
}
Also, your declaration of pointer is unnecessary because it is pointing to the exact same position as arr. You can check this with printf("%p %p\n",arr,pointer);
How much of the string is printed is controlled by the NULL-character "\0", which C automatically appends to every string. If you wish to print out just a portion, either override a character in the string with a "\0", or use the fwrite function or something similar to write just a few bytes to stdout.
You could achieve the objective with a small function, say substring.
#include<stdio.h>
#include<string.h> // for accessing strlen function
void substring(char* c,int len)
{
if (len <= strlen(c)){
*(c+len)='\0';
printf("%s\n",c);
}
else{
printf("Sorry length, %d not allowed\n",len);
}
}
int main(void)
{
char c[]="teststring";
char* ptr=c;
substring(ptr,4); // 4 is where you wish to trim the string.
return 0;
}
Notes:
In C++ a built-in function called substring is already available which shouldn't be confused with this.
When a string is passed to a function like printf using a format specifier %s the function prints all the characters till it reaches a null character or \0. In essence, to trim a string c to 4 characters means you put c[4] to null. Since the count starts from 0, we are actually changing the 5th character though. Hope the example makes it more clear.

Pointer array and structure in C

I am nowhere lose to even guessing how come we get the given output . Can I please get some explanation? Also, any short and quick resources to try similar questions?
void main()
{
struct a
{
char ch[10];
char *str;
};
struct a s1={"Hyderabad","Bangalore"};
printf("\n%c%c",s1.ch[0],*s1.str);
printf("\n%s%s",s1.ch,s1.str);
getch();
}
Ans: HB, HyderabadBangalore
struct a s1={"Hyderabad","Bangalore"}; assigns "Hyderabad" to ch and "Bangalore" to str.
printf("\n%c%c",s1.ch[0],*s1.str); prints the first character of the strings. Since ch is an array, ch[0] represents its first character. Since str is a character pointer, it points to the first character of a string here. So, *s1.str will have value 'B'
printf("\n%s%s",s1.ch,s1.str); simply prints all characters of both strings.
Fundamentally, ch is equal to &ch[0], the address of the first character in the array. And, str is pointer variable which holds the address of first character of the string literal "Bangalore".
%c is only for single character. Example H.
$s is for string. Example Hyderabad.
s1.ch[0] points to first character of String ch ->H
*s1.str is a pointer. It points to the value stored at address of str. It will be ->B
Hence you get HB
\n means a new line (as in java).
Here is your output according to requested question
void main()
{
struct a
{
char ch[10];
char *str;
};
struct a s1={"Hyderabad","Bangalore"};
printf("%c%c",s1.ch[0],*s1.Str[0]);
printf("\t%s%s",s1.ch,s1.str);
getch();
}

Resources