Unexpected output at the end of printing an array of char - c

#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.

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.

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.

Undefined behavior of a program

While writing a program i am filling the entries of a char array with digits. After doing so the length calculated for an array having no zero is correct but for an array starting with zero is zero!
Why is this result coming so!I am not able to interpret my mistake!?
int main()
{
int number_of_terms,no,j,i;
char arr[100];
char c;
scanf("%d",&number_of_terms);
for(i=0;i<number_of_terms;i++)
{
j=0;
while(c!='\n')
{
scanf("%d",&arr[j]);
if(c=getchar()=='\n')
break;
j++;
}
printf("Length is:%d\n",strlen(arr));
}
return 0;
}
for eg if i input my array elements as 4 5
lenght is 2
and if my array elements as 0 5
length is 0..
You are using "%d" in your format specifier, which produces an integer, and you are passing in the address of a character array. This is, exactly like your title says, undefined behaviour. In particular, the value zero will take up 4 of the cells in your string, and will write zero to all of those. Since the character with value zero is the end marker, you get zero length string. However, on another architecture, the second character would probably cause a crash...
If you want to store integers in an array, you should use int arr[...];. If you want to store characters, use "%c".
You are copying the value 0 into the array. This eqals the character '\0' which is used to terminate strings. What you want is to copy the character '0' (has the value 48, see an ascii table).
Change %d to %c to interpret the input has character instead of decimal.
scanf("%c",&arr[j]);
Also your "string" in arr is not zero terminated. After all the characters of your string, you have to end the string with the value 0 (here a decimal is correct). strlen needs it, because it determines the length of the string by traversing the array and counting up until it finds a 0.

Unexpected output when printing element of array in 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;
}

Resources