How can i fix a problem with character array? - c++

I have set the size of the character array to 2 bytes. But it can hold more than 2 bytes. how is it possible?
#include<iostream>
int main() {
char a[2];
std::cout << "enter the name" << std::endl;
std::cin >> a;
std::cout << "the name is " << a << std::endl;
system("pause");
return 0;
}
I am expecting some other output
but the output is .....
enter the name
Sami
the name is Sami

What happens is that you are effectively writing past the end of the allocated memory.
C++ doesn't check that the input provided fits intothe variable a so you are actually writing out of the bounds of the memory allocated to your program, resulting in Undefined Behaviour.
Your program seems to work, but you have actually no guarantees that it will behave as you wish.

Don't use a fixed size array of char, but use std::string instead.
Here is a fixed code example.
#include<iostream>
#include<string>
int main() {
std::string a;
std::cout << "enter the name" << std::endl;
std::getline(std::cin, a);
std::cout << "the name is " << a << std::endl;
system("pause");
return 0;
}

Related

How do I print const char?

#include <iostream>
using namespace std;
int main() {
int age = 20;
const char* pDept = "electronics";
cout << age << " " << pDept;
}
The above code is normal.
Why shouldn't I use cout << *pDept instead of cout << pDept above?
Both of them are legal in C++. Which one to use depends on what you want to print.
In your case, pDept is a pointer that points to a char in memory. It also can be used as a char[] terminated with \0. So std::cout << pDept; prints the string the pointer is pointing to.
*pDept is the content that pDept points to, which is the first character of the string. So std::cout << *pDept; prints the first character only.

Sizeof operator on string array is giving different output in C++

I am trying to compile the following code:
#include <iostream>
using namespace std;
void show1(string text1[]) {
cout << "Size of array text1 in show1: " << sizeof(text1) << endl;
}
int main() {
string text1[] = {"apple","melon","pineapple"};
cout << "Size of array text1: " << sizeof(text1) << endl;
cout << "Size of string in the compiler: " << sizeof(string) << endl;
show1(text1);
return 0;
}
And the output is shown below:
Size of array text1: 96
Size of string in the compiler: 32
Size of array text1 in show1: 8
I am not able to understand, why is the sizeof operator working on the same array giving two different outputs at two different points? Please explain.
The sizeof() operator returns the compile time size of the objects. It means that if your type allocates a memory chunk at run time from heap, that memory is not taken into account by sizeof().
For your first case, i.e.
string text1[] = {"apple","melon","pineapple"};
You have an array of 3 strings, so sizeof should return 3*sizeof(std::string). (3*32 = 96 in your case)
For your second case:
sizeof(string)
It should simply print the size of an string. (32 in your case).
Finally for your last case, do not forget that arrays are passed using a pointer in C/C++. So, your parameter is simply a pointer and sizeof() should print the size of a pointer on your machine.
Edit: As #ThomasMatthews has mentioned in the comments, if you are interested in getting the real size of an string (i.e. the number of characters inside it), you can use std::string::length() or std::string::size().
Try with member function 'size'.
Write this code:
#include <iostream>
using namespace std;
void show1(string text1[])
{
cout << "Size of array text1 in show1: " << text1->size() << endl;
}
int main()
{
string text1[] = {"apple","melon","pineapple"};
cout << "Size of array text1: " << text1->size() << endl;
cout << "Size of string in the compiler: " << sizeof(string) << endl;
show1(text1);
return 0;
}
Description:
std::vector has a member function size(). And std::string too. In std::vector return size of vector(all elements). In std::string returns all elements in array.

cout and String concatenation

I was just reviewing my C++. I tried to do this:
#include <iostream>
using std::cout;
using std::endl;
void printStuff(int x);
int main() {
printStuff(10);
return 0;
}
void printStuff(int x) {
cout << "My favorite number is " + x << endl;
}
The problem happens in the printStuff function. When I run it, the first 10 characters from "My favorite number is ", is omitted from the output. The output is "e number is ". The number does not even show up.
The way to fix this is to do
void printStuff(int x) {
cout << "My favorite number is " << x << endl;
}
I am wondering what the computer/compiler is doing behind the scenes.
The + overloaded operator in this case is not concatenating any string since x is an integer. The output is moved by rvalue times in this case. So the first 10 characters are not printed. Check this reference.
if you will write
cout << "My favorite number is " + std::to_string(x) << endl;
it will work
It's simple pointer arithmetic. The string literal is an array or chars and will be presented as a pointer. You add 10 to the pointer telling you want to output starting from the 11th character.
There is no + operator that would convert a number into a string and concatenate it to a char array.
adding or incrementing a string doesn't increment the value it contains but it's address:
it's not problem of msvc 2015 or cout but instead it's moving in memory back/forward:
to prove to you that cout is innocent:
#include <iostream>
using std::cout;
using std::endl;
int main()
{
char* str = "My favorite number is ";
int a = 10;
for(int i(0); i < strlen(str); i++)
std::cout << str + i << std::endl;
char* ptrTxt = "Hello";
while(strlen(ptrTxt++))
std::cout << ptrTxt << std::endl;
// proving that cout is innocent:
char* str2 = str + 10; // copying from element 10 to the end of str to stre. like strncpy()
std::cout << str2 << std::endl; // cout prints what is exactly in str2
return 0;
}

C++ Array passed by reference, but how to understand this?

The arrays are passed by reference. Any changes made to the array within the function changeArray will be observed in the calling scope (main function here).
However the codes below print 0 1 in the 1st cout, and print 2 in the 2nd "cout". What I don't understand is that why the first cout prints the original value of array[0]=1 instead of the changed value of array[0]=2?
Thanks a lot.
#include <iostream>
using namespace std;
int changeArray(int array[]) {
array[0]=2*array[0];
return 0;
}
int main() {
int array[]={1,2,3,4};
cout << changeArray(array) << " " << array[0] << endl;
cout << array[0] << endl;
return 0;
}
To make sure that the compiler doesn't reorder the execution:
cout << array[0] << endl;
changeArray(array);
cout << array[0] << endl;
This prints 1 and then 2.
The C++ compiler is allowed to optimize the code by reordering the execution of code within a single expression (e.g. cout << changeArray(array) << " " << array[0] << endl). To avoid that, and to make sure changeArray gets called first, you need to split your expression to separate statements, e.g. by using the semicolon (;). Everything before the semicolon gets executed before anything after the semicolon can start.

Converting char* to int after using strdup()

Why after using strdup(value) (int)value returns you different output than before?
How to get the same output?
My short example went bad, please use the long one:
Here the full code for tests:
#include <stdio.h>
#include <iostream>
int main()
{
//The First Part
char *c = "ARD-642564";
char *ca = "ARD-642564";
std::cout << c << std::endl;
std::cout << ca << std::endl;
//c and ca are equal
std::cout << (int)c << std::endl;
std::cout << (int)ca << std::endl;
//The Second Part
c = strdup("ARD-642564");
ca = strdup("ARD-642564");
std::cout << c << std::endl;
std::cout << ca << std::endl;
//c and ca are NOT equal Why?
std::cout << (int)c << std::endl;
std::cout << (int)ca << std::endl;
int x;
std::cin >> x;
}
Because an array decays to a pointer in your case, you are printing a pointer (ie, on non-exotic computers, a memory address). There is no guarantee that a pointer fits in an int.
In the first part of your code, c and ca don't have to be equal. Your compiler performs a sort of memory optimization (see here for a full answer).
In the second part, strdup allocates dynamically a string twice, such that the returned pointers are not equal. The compiler does not optimize these calls because he does not seem to control the definition of strdup.
In both cases, c and ca may not be equal.
"The strdup() function shall return a pointer to a new string, which is a duplicate of the string pointed to by s1." source
So it's quite understandable that the pointers differ.