Unexpected output when printing element of array in c - c

I am creating a simple c program and output of below program should be 2 but i am getting 50 dont know why (i am newbie to c) please let me know where i am missing
#include<stdio.h>
int main(int argc, char** argv) {
int a[4]={'1','2','2','\0'};
printf("The value of a is %d",a[1]);
return 0;
}
here is live output

You initialised the array using ascii character codes. '2' has integer value 50.
Initialise the array as
int a[4]={1,2,2,0};
if you want it to contain integers 1,2,2,0. Or
#include<stdio.h>
int main(int argc, char** argv) {
char a[4]="121";
printf("The value of a is %c",a[1]);
return 0;
}
if you want an array of characters that can be treated as a string. (Note the use of the %c format specifier here.)

50 is the ASCII code of '2'.
Replace '2' with 2 if you want it fixed.
When using character literals like '2' C actually thinks of them as integer types. When you print it using %d format specifier you're telling C to print the value as integer.
If you want to keep the array elements like this: '2', you'll need to change printf format to %c to get a 2 in the console.

When you wrote int a[4]={'1','2','2','\0'}; you actually initialized the array with ASCII Codes of the numbers 1 and 2.
This is because you enclosed them within single quotes thus making them characters instead of integers.
Hence the array actually takes the values int a[4]={49,50,50,0};
To rectify it, you should write the integers without the quotes:
int a[4]={1,2,2,0};
Also note that integer arrays don't need to end with '\0'. That is only for character arrays.

This line
int a[4]={'1','2','2','\0'};
tells the compiler to create an integer array of length 4 and put into it the integers from the curled braces from the right.
Characters in C are 1-byte integers, 1 is a character of 1 and it means integer value of it's ASCII code, i.e. 50. So the first element of an array gets the value of 50.
To fix you should write
int a[4]={1,2,2,0};
remember, that 0 cannot serve as an array end marker, since it is just a number.
If you suppose to get 122 output then do
char a[4]={'1','2','2','\0'};
printf("The value of a is %s",a);
since strings in C are character arrays with 0 as termination symbol.
Also you can let compiler to count values for you
char a[]={'1','2','2','\0'};

You are assigning chars not integers:
note
'2' means char use %c
2 manes int use %d
"2" means string. use %s
all are different:
in your code you can do like to print 2:
int main(int argc, char** argv) {
char a[4]={'1','2','2','\0'};
printf("The value of a is %c",a[1]);
return 0;
}

Related

How does a null character behave in a char array in C?

I tried to reverse this char array with null characters in the middle and the end, without using string length. (original code)
#include <stdio.h>
#include <stdlib.h>
int main()
{
char string[4] ={'c', '\0', 's', '\0'};
printf("What do we love?\n");
printf("Yes, we love:");
for(int i=3; i>=0; i--){
printf("%d", string[i]);
}
return 0;
}
I expected the output to display nothing. But I got the reverse of the array with whitespaces at the places where I’m guessing are the null characters? (output)
Bcoz I have tried using %d too instead of %c and found that those spaces apparently do have the ascii value of 0. (code with slight change + output + ascii table)
So, does this mean that a loop will not always treat a null character in a char array as an indicator of termination? Does this also mean null characters, which automatically get appended on the empty spaces of a char array actually, get printed as spaces in display, but we just say that it prints nothing in the output after it encounters null character only coz we see 'nothing' on display with most codes?
A null byte is used in a char array to designate the end of a string. Functions that operate on strings such as strcpy, strcmp, and the %s format specifier for printf, will look for a null byte to find the end of a string.
You're not treating string as a string, but as just an array of char. So it doesn't matter whether or not a particular element of the array has the value 0 as you're not treating that value as special in any way. You're just printing the decimal value of each of the elements of the array.

+'0' wont give char value of int

I was trying to make this int to char program. The +'0' in the do while loop wont convert the int value to ascii, whereas, +'0' in main is converting. I have tried many statements, but it won't work in convert() .
#include<stdio.h>
#include<string.h>
void convert(int input,char s[]);
void reverse(char s[]);
int main()
{
int input;
char string[5];
//prcharf("enter int\n");
printf("enter int\n");
scanf("%d",&input);
convert(input,string);
printf("Converted Input is : %s\n",string);
int i=54;
printf("%c\n",(i+'0')); //This give ascii char value of int
printf("out\n");
}
void convert(int input,char s[])
{
int sign,i=0;
char d;
if((sign=input)<0)
input=-input;
do
{
s[i++]='0'+input%10;//but this gives int only
} while((input/=10)>0);
if(sign<0)
s[i++]='-';
s[i]=EOF;
reverse(s);
}
void reverse(char s[])
{
int i,j;
char temp;
for(i=0,j=strlen(s)-1;i<j;i++,j--)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
Output screenshot
Code screenshot
The +'0' in the do while loop wont convert the int value to ascii
Your own screenshot shows otherwise (assuming an ASCII-based terminal).
Your code printed 56, so it printed the bytes 0x35 and 0x36, so string[0] and string[1] contain 0x35 and 0x36 respectively, and 0x35 and 0x36 are the ASCII encodings of 5 and 6 respectively.
You can also verify this by printing the elements of string individually.
for (int i=0; string[i]; ++i)
printf("%02X ", string[i]);
printf("\n");
I tried your program and it is working for the most part. I get some goofy output because of this line:
s[i]=EOF;
EOF is a negative integer macro that represents "End Of File." Its actual value is implementation defined. It appears what you actually want is a null terminator:
s[i]='\0';
That will remove any goofy characters in the output.
I would also make that string in main a little bigger. No reason we couldn't use something like
char string[12];
I would use a bare minimum of 12 which will cover you to a 32 bit INT_MAX with sign.
EDIT
It appears (based on all the comments) you may be actually trying to make a program that simply outputs characters using numeric ascii values. What the convert function actually does is converts an integer to a string representation of that integer. For example:
int num = 123; /* Integer input */
char str_num[12] = "123"; /* char array output */
convert is basically a manual implementation of itoa.
If you are trying to simply output characters given ascii codes, this is a much simpler program. First, you should understand that this code here is a mis-interpretation of what convert was trying to do:
int i=54;
printf("%c\n",(i+'0'));
The point of adding '0' previously, was to convert single digit integers to their ascii code version. For reference, use this: asciitable. For example if you wanted to convert the integer 4 to a character '4', you would add 4 to '0' which is ascii code 48 to get 52. 52 being the ascii code for the character '4'. To print out the character that is represented by ascii code, the solution is much more straightforward. As others have stated in the comments, char is a essentially a numeric type already. This will give you the desired behavior:
int i = 102 /* The actual ascii value of 'f' */
printf("%c\n", i);
That will work, but to be safe that should be cast to type char. Whether or not this is redundant may be implementation defined. I do believe that sending incorrect types to printf is undefined behavior whether it works in this case or not. Safe version:
printf("%c\n", (char) i);
So you can write the entire program in main since there is no need for the convert function:
int main()
{
/* Make initialization a habit */
int input = 0;
/* Loop through until we get a value between 0-127 */
do {
printf("enter int\n");
scanf("%d",&input);
} while (input < 0 || input > 127);
printf("Converted Input is : %c\n", (char)input);
}
We don't want anything outside of 0-127. char has a range of 256 bits (AKA a byte!) and spans from -127 to 127. If you wanted literal interpretation of higher characters, you could use unsigned char (0-255). This is undesirable on the linux terminal which is likely expecting UTF-8 characters. Values above 127 will be represent portions of multi-byte characters. If you wanted to support this, you will need a char[] and the code will become a lot more complex.

Unexpected output at the end of printing an array of char

#include <stdio.h>
int main(int argc, const char * argv[]) {
  unsigned char ch,i,letters[95];
int tapped [0];
ch=32; //start with 32 (space)
while(ch<=127){
ch++;
letters[i]=ch;
i++;
} 
printf(letters);
return 0;
}
I'm trying to get the ASCII characters from 32 to 127 into an array so I can generate N random ones in another loop.
The issue is that I'm getting back all of them, but I'm also getting back some additional unexpected at the end:
!"#$%&'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~\200\300\367\277_\377
I don't understand why I'm getting \200\300\367\277_\377 at the end, since they aren't in the range. I'm new to C so is there some aspects of arrays that I'm not doing properly?
First, if you count the characters from 32 to 127, there are 96 of them. So letters should be defined with letters[96], not letters[95].
Second, you should not pass letters to printf as the first parameter. The first parameter should be a format string, not a string to be printed literally. In particular, since letters contains a “%” character, it is not a proper format string.
Third, when printing a string, printf expects a null-terminated string by default. To print an array of char that is not null-terminated, you can use a precision in the conversions specifier:
printf("%.96s\n", letters);
Fourth, you say you want all the characters from 32 to 127, but your loop starts with ch set to 32 and increments it before putting it into the array, so the first value put into the array is 33. You should nove the increment to later.
Fifth, you do not initialize i. It must be set to zero before starting the loop.

printing int array as string

I am trying to print int array with %s. But it is not working. Any ideas why?
#include<stdio.h>
main() {
int a[8];
a[0]='a';
a[1]='r';
a[2]='i';
a[3]='g';
a[4]='a';
a[5]='t';
a[6]='o';
a[7] = '\0';
printf("%s", a);
}
It prints just a.
I tried with short as well, but it also does not work.
This is because you are trying to print a int array, where each element has a size of 4 byte (4 chars, on 32bit machines at least). printf() interprets it as char array so the first element looks like:
'a' \0 \0 \0
to printf(). As printf() stops at the first \0 it finds, it only prints the 'a'.
Use a char array instead.
Think about the way integers are represented - use a debugger if you must. Looking at the memory you will see plenty of 0 bytes, and %s stops when it reaches a 0 byte.
It prints just a.
That's why it prints just a. Afterwards it encounters a 0 byte and it stops.
Because you declared a as an integer, so those signle characters you initialized would result in an error. You must change it to a char variable. However to save time, just make the variable a pointer using the asterisk character, which then allows you to make a single string using double quotes.
int a[8] means array of 8 ints or 8*(4 bytes) - Say 32 bit architecture
a[0] = 'a' stores in the first int index as 'a''\0''\0''\0'
a[1] = 'r' as 'r''\0''\0''\0' and so on . . .
%s represents any C-style string ie. any string followed by a '\0' character
So
printf("%s", a);
searches for trailing '\0' character and just prints "a" assuming it is the entire string

Convert a char to an int in C

I want to make a program which converts 3www2as3com0 to www.as.com but I have got trouble at the beginning; I want to convert the first number of the string (the character 3) to an integer to use functions like strncpy or strchr so when I print the int converted the program shows 51 instead of 3. What is the problem?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv) {
/* argv[1]--->3www2as3com0*/
char *string;
char *p;
string=argv[1];
p=string;
char cond,cond2;
cond=*p; //I want to have in cond the number 3
cond2=(int)cond; //I want to convert cond (a char) to cond2(an int)
printf("%d",cond2); //It print me 51 instead of 3
return (EXIT_SUCCESS);
}
Your computer evidently encodes strings in a scheme called ASCII . (I am fairly sure most modern computers use ASCII or a superset such as UTF-8 for char* strings).
Notice how both printable and nonprintable characters are encoded as numbers. 51 is the number for the character '3'.
One of the nice features of ASCII is that all the digits have increasing codes starting from '0'.
This allows one to get the numerical value of a digit by calculating aDigitCharacter - '0'.
For example: cond2 = cond - '0';
EDIT:
You should also probably also double check that the character is indeed a digit by making sure it lies between '0' and '9';
If you want to convert a string containing more than one digit to a number you might want to use atoi.
It can be found in <stdlib.h>.
The character's integer value is the ASCII code for the digit, not the number it actually represents. You can convert by subtracting '0'.
if( c >= '0' && c <= '9' ) val = c - '0';
Seems like the strings you are using will never have negative number, so you can use atoi(), returns the integer value from char. If it encounters something that is not a number, it will get the number that builds up until then.

Resources