Reputation: 1260
I don't understand why there are random char after abc
. what is the reason? How to print out only abc
? Thanks!
#include <stdio.h>
int main()
{
char arr[3];
char(*ptr)[3]; // declare a pointer to an array
arr[0] = 'a';
arr[1] = 'b';
arr[2] = 'c';
ptr = &arr;
printf("%s\n", arr);
//printf("%s\n", ptr);
return 0;
}
Upvotes: 3
Views: 1573
Reputation: 310910
The reason of the random characters is that you are trying to output the array as a string using the conversion specifier %s
.
But the character array arr
does not contain a string (a sequence of characters terminated by the zero character '\0'
).
So to output it using the function printf
you can do for example the following way:
printf( "%*.*s\n", 3, 3, arr );
From the C Standard (7.21.6.1 The fprintf function)
4 Each conversion specification is introduced by the character %. After the %, the following appear in sequence:
— An optional precision that gives ... the maximum number of bytes to be written for s conversions.
Upvotes: 4
Reputation: 1086
The string need to be terminated with a \0
. Make sure to allocate enough space to store the terminator as well.
#include <stdio.h>
int main()
{
char arr[4];
char(*ptr)[4]; // declare a pointer to an array
arr[0] = 'a';
arr[1] = 'b';
arr[2] = 'c';
arr[3] = '\0'; // <-- terminator
ptr = &arr;
printf("%s\n", arr);
//printf("%s\n", ptr);
return 0;
}
Note that using char arr[4]
you will have random content in your array. If instead you would use
char arr[4] = "abc";
This will lead to
char arr[4] = {'a', 'b', 'c', 0};
See how the other places are filled with a 0
so you don't have to set it yourself.
Upvotes: 7
Reputation: 156
String must be terminated with 0
.
So you have to declare 4 element array.
char arr[4] = "abc";
The strlen
function wich all printf function family uses, reads string till 0
value is found.
So strlen
returned length of memory block that starts at your array beginning and ends with first zero.
This can cause undefined behavior.
Upvotes: 0