c++ store address of next position of the array - c++

I have an array that I want to store the address of the next array in the current position.
So far I have
char *a = new char[50];
char *free = a;
*a = &(a + 1); //value of a[0] is equal to the address of a[1]
Also I'm using a char array so I'm sure I'll need to cast some stuff.
Any help would be nice.

You can't store a char* in a char array.
A character is equal to one byte. The size of a pointer, such as char*, varies depending on your computer. On my computer, its 8 bytes. 8 bytes can't fit in 1 byte.
#include <iostream>
int main()
{
std::cout << "sizeof(char): " << sizeof(char) << std::endl;
std::cout << "sizeof(char*): " << sizeof(char*) << std::endl;
return 0;
}
// Outputs
// sizeof(char): 1
// sizeof(char*): 8
You also won't be able to cast a char* to a char to fit it in the array either, as your compiler will yell at you.
#include <iostream>
int main()
{
char myArray[10];
std::cout << (char)&myArray[0];
}
// Compiler error:
// g++ main.cpp -std=gnu++11
// main.cpp: In function ‘int main()’:
// main.cpp:7:34: error: cast from ‘char*’ to ‘char’ loses precision [-fpermissive]
The closest thing you can do to get this working is to use an array of size_t. size_t is the size of a pointer. So the number of bytes in size_t and size_t* is equal, and therefore you can put a size_t* in an array of size_t... after casting.
#include <iostream>
int main()
{
size_t myArray[10];
myArray[0] = reinterpret_cast<size_t>(&myArray[1]);
std::cout << std::hex << "0x" << myArray[0] << std::endl;
}
// Outputs: 0x7fff4eded5c8
Also, consider using indicies[] instead of pointer addition. Its more readable, and it does the same thing under the hood. a[1] == *(a+1).

Related

The address of C ++ pointer

#include <iostream>
using namespace std;
int main(int argc, char** argv) {
unsigned int a =5;
unsigned int *pint = NULL;
cout << "&a = " << &a << endl;
cout << " &pint = " << &pint << endl;
}
Output:
&a = 0x6ffe04
&pint = 0x6ffdf8
I'm wondering why the address of pint equals 0x6ffdf8. pint is an unsigned int (4 bytes), shouldn't the address of it be 0x6ffe00?
Your pint is not an unsigned int. It is a pointer to an unsigned int.
Pointer can have a different size and can especially have the size 8.
It could hence fit into 0x6ffdfc before 0x6ffe04.
But it also has bigger alignment needs, it wants an address dividable by 8, so 0x...c is out, it needs e.g. 0x...8.
With 463035818_is_not_a_number I agree that this not really predictable, there are implementation specific aspects. That is why I phrase "softly" with "can", "wants", "e.g."....

How can I calculate size of Array in C++

I had the online coding interview today and I really struggled while trying to calculate the size of the array.
Could you please help me with how can I measure the sizeof array here? I tried my best but no luck please help here.
#include<iostream>
#include<map>
#include<vector>
using namespace std;
void arraysize(int* a) {
cout << "size1: "<<sizeof(a) << endl;
cout << "size2: " << sizeof(a[0]) << endl;;
}
int main()
{
int array1[] = { 1,2,3,4,5,6,7,8 };
arraysize(array1);
return 0;
}
Result:
size1: 4
size2: 4
In most cases, when you pass an array to a function, the array will be converted to a pointer. This is called an array-to-pointer decay. Once this decay happens, you lose the size information of the array. That is, you can no longer tell the size of the original array from the pointer.
However, one case in which this conversion / decay will not happen is when we pass a reference to the array. We can take advantage of this property to get the size of an array.
#include<iostream>
template<typename T, size_t N>
size_t asize(T (&array)[N])
{
return N;
}
int main()
{
int array1[] = { 1,2,3,4,5,6,7,8 };
std::cout << asize(array1) << std::endl; // 8
return 0;
}
In the above case, to the template function asize, we pass a reference to an array of type T[N], whose size is N. In this case, it is array type int[8]. So the function returns N, which is size 8.
C style array's decay to pointer's when passed to a function like this.
The first cout statement is printing the size of a pointer on your machine.
The second cout statement is printing the size of an integer.
Use one of the following solutions in order to pass the size of the array to the function.
template<std::size_t N>
void ArraySize( int ( &array )[ N ] )
{
std::cout << "Array size: " << N << '\n';
}
void ArraySize( int* array, std::size_t size )
{
std::cout << "Array size: " << size << '\n';
}
template<std::size_t N>
void ArraySize( std::array<int, N>& array )
{
std::cout << "Array size: "<< array.size( ) << '\n';
}
sizeof(a) returns the number of bytes in array,
sizeof(int) returns the number of bytes in an int,
ergo
sizeof(a)/sizeof(int) returns the array length
Easiest way to get the size of an array:
#include <iostream>
using namespace std;
int main(void) {
int ch[5], size;
size = sizeof(ch) / sizeof(ch[0]);
cout << size;
return 0;
}
Output: 5
simply divide sizeof(array1) by sizeof(int). it will give you total element in array. because sizeof(array1) will give total bytes in the array. for example sizeof(array1) = int * 8 because your array is int so int is 4 byte answer is 4*8 = 32.Now you have to divide it again by 4 cause its in byte.
cout << "Size of the Array is : " << sizeof(array1)/sizeof(int) << endl;
put above code in your main function to get result

cpp double pointer vs 2 dimensional array pointer

#include <iostream>
int main() {
int a[2][2] = {{1,2}, {3,4}};
int *c = *a;
int **b = &c;
std::cout << **(a+1); // outputs 3
std::cout << **(b+1); // segmentation fault
}
Why does one cout results in segmentation fault and other doesn't? Shouldn't they be referring to the same value?
Lets start with
int *c;
Actually what comes before is not that relevant, because c is just a pointer and then here
int **b = &c;
you store the address of c in b. The address of c has nothing to do with what value is stored in c. c is just a pointer, taking its adress doesn't let you magically access a 2d array.
cout << **(b+1); // segmentation fault
Already b+1 is undefined behaviour. Dereferencing that pointer cannot give you something meaningful.
PS: tbh I cannot tell you how to use the double pointers correctly here. Once I started to learn c++ I unlearned anything I knew about working with arrays via pointers. Use std::vector or std::array and save yourself some headaces.
In this statement
cout << **(b+1);
the expression b+1 points outside the array (that is more precisely outside the object c). You should write
cout << *( *b + 2 );
The dereferenced pointer b points to the pointer to the first element of the two-dimensional array. When adding to it the number of elements in the array of the type int[2] you will get the pointer to the first element of the second "row" of the two-dimensional array. Now you need again to dereference it to output the pointed value.
I rewrote the code to highlight what is happening, as below:
#include <iostream>
int main() {
int a[2][2] = {{1,2}, {3,4}};
int *c[2] = {a[0], a[1]};
int **b = c;
std::cout << **(a ) << ','; // outputs 1
std::cout << **(b ) << ";\n"; // outputs 1
std::cout << **(a+1) << ','; // outputs 3
std::cout << **(b+1) << ";\n"; // outputs 3
}
LINK: https://ideone.com/ixj3NV
UPDATED LINK: https://ideone.com/g7jjVN
(Clarified the original source to extend the program)

C++ strlen(ch) and sizeof(ch) strlen

I have this code:
int main()
{
char ch[15];
cout<<strlen(ch)<<endl; //7
cout<<sizeof(ch)<<endl; //15
return 0;
}
Why does strlen(ch) give different result even if it is empty char array?
Your code has undefined behavior because you are reading the uninitialized values of your array with strlen. If you want a determinate result from strlen you must initialize (or assign to) your array.
E.g.
char ch[15] = "Hello, world!";
or
char ch[15] = {};
sizeof will give the size of its operand, as the size of char is one by definition the size of a char[15] will always be 15.
strlen gives the length of a null terminated string which is the offset of the first char with value 0 in a given char array. For a call to strlen to be valid, the argument to must actually point to a null terminated string.
ch is a local variable and local variables are not initialized. So your assumption that it is an empty string is not correct. Its filled with junk. It was just a co-incidence that a \0 character was found after 7 junk characters and hence strlen returned 7.
You can do something like these to ensure an empty string-
char ch[15]={0};
ch[0]='\0`;
strcpy(ch,"");
Here's a similar thread for more reading
Variable initialization in C++
The problem is in
strlen(ch);
strlen counts the number of chars, untill hitting the \0 symbol. Here, ch is non-initialized, so strlen could return anything.
As for the result from strlen, in your case you have an uninitialized char array, and so strlen only happens to yield 7: there must be a null character at array element 8, but this code could give different results for strlen every time.
Always initialize strings, it's easy enough with an array: char str[15] = {0};
sizeof is an operator used to get the size of a variable or a data type, or the number of bytes occupied by an array, not the length of a C string; don't expect strlen and strcpy to be interchangeable, or even comparable in any useful way.
For instance:
int main()
{
char str[15] = "only 13 chars";
cout << "strlen: " << strlen(str) << endl;
cout << "sizeof: " << sizeof(str) << endl;
}
The output is:
strlen: 13
sizeof: 15
Returns the length of str.
The length of a C string is determined by the terminating
null-character: A C string is as long as the amount of characters
between the beginning of the string and the terminating null
character.
sizeof returns number of bytes (15). Your array is filled by garbage, so, strlen can returns any number. Correct example is
int main()
{
char ch[15] = {0};
cout<<strlen(ch)<<endl; //0
cout<<sizeof(ch)<<endl; //15
return 0;
}
The difference between sizeof and strlen in C++:
1) sizeof is a operator, strlen is a function;
2) The return type of sizeof is size_t,and it is defined (typedef) as unsigned int in its header; It gets the byte size of the memory allocation which can maximize to accommodate this object to be created in memory;
3) sizeof can use type as a parameter, while strlen can only use char pointer (char*) as a pointer, and it must be ended as '\0';
sizeof can also use function as a parameter, for instance:
short f() {return 100;}
std::cout << "sizeof(f()): " << sizeof(f()) << std::endl;
//The result will be sizeof(short), which is 2.
4) If char array is a parameter, it will not be degraded by sizeof, while strlen will degrade it as a char pointer;
5) The result of strlen will be calculated in the run time, not compilation time, strlen is used to get the real size of the content of a string (string, char array, char pointer) until the '\0', not the real size of memory allocation. Most of the compiler will calculate the result of sizeof in the compilation time, no matter the parameter is type or variable, that is why sizeof(x) can be used to decide the dimension of an array:
char str[20]="0123456789";
int a=strlen(str); //a=10;
int b=sizeof(str); //while b=20;
7) If the parameter of sizeof is a type, then parentheses are mandatory, while if the parameter is a variable, parentheses are optional, because sizeof is an operator not a function;
8) When you use a structured type or variable as a parameter, sizeof will return its real size, when you use a static array, sizeof will return the array size. But sizeof operator cannot return the size of an array which is created dynamically or externally. Because sizeof is a compilation time operator.
Here is an example of sizeof and strlen:
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
short f1 ()
{
return 100;
}
int f2 ()
{
return 1000;
}
int main()
{
char* char_star = "0123456789";
// char_star is a char pointer, sizeof will return the pointer size allocated in memory: depends on your machine
std::cout << "sizeof(char_star):" << sizeof(char_star) << std::endl;
// *char_star is the first element of the string, it is a char, sizeof will return the char size allocated in memory: depends on your machine, normally is 1
std::cout << "sizeof(*char_star):" << sizeof(*char_star) << std::endl;
// char_star is a char pointer, strlen will return the real size of the string until '\0': 10
std::cout << "strlen(char_star):" << strlen(char_star) << std::endl;
std::cout << std::endl;
char char_array[] = "0123456789";
// char_array is a char array, sizeof will return the array size allocated in memory, with a '\0' at the end: 10 + 1
std::cout << "sizeof(char_array):" << sizeof(char_array) << std::endl;
// *char_array is the first element of the array, it is a char, sizeof will return the char size allocated in memory: depends on your machine, normally is 1
std::cout << "sizeof(*char_array):" << sizeof(*char_array) << std::endl;
// char_array is a char array, strlen will return the real size of the string until '\0': 10
std::cout << "strlen(char_array):" << strlen(char_array) << std::endl;
std::cout << std::endl;
char_array_fixed[100] = "0123456789";
// char_array_fixed is a char array with fixed size, sizeof will return the array size allocated in memory: 100
std::cout << "sizeof(char_array_fixed):" << sizeof(char_array_fixed) << std::endl;
// *char_array_fixed is the first element of the array, it is a char, sizeof will return the char size allocated in memory: depends on your machine, normally is 1
std::cout << "sizeof(*char_array_fixed):" << sizeof(*char_array_fixed) << std::endl;
// *char_array_fixed is a char array with fixed size, strlen will return the real content size of the string until '\0': 10
std::cout << "strlen(char_array_fixed):" << strlen(char_array_fixed) << std::endl;
std::cout << std::endl;
int int_array[100] = {0,1,2,3,4,5,6,7,8,9};
// int_array is a int array with fixed size, sizeof will return the array size allocated in memory: 100
std::cout << "sizeof(int_array):" << sizeof(int_array) << std::endl;
// *int_array is the first element of the array, it is an int, sizeof will return the int size allocated in memory: depends on your machine, normally is 4
std::cout << "sizeof(*int_array):" << sizeof(*int_array) << std::endl;
// int_array is a int array with fixed size, strlen will throw exception
//std::cout << "strlen(int_array):" << strlen(int_array) << std::endl;
std::cout << std::endl;
char char_array2[] = {'a', 'b', '3'};
// char_array2 is a char array, sizeof will return the array size allocated in memory: 3
std::cout << "sizeof(char_array2):" << sizeof(char_array2) << std::endl;
// *char_array2 is the first element of the array, it is a char, sizeof will return the char size allocated in memory: depends on your machine, normally is 1
std::cout << "sizeof(*char_array2):" << sizeof(*char_array2) << std::endl;
// *char_array2 is a char array, strlen will return the real content size of the string until '\0': 3
std::cout << "strlen(char_array2):" << strlen(char_array2) << std::endl;
std::cout << std::endl;
char char_array3[] = {"abc"};
// char_array3 is a char array, sizeof will return the array size allocated in memory, with a '\0' at the end : 3 + 1
std::cout << "sizeof(char_array3):" << sizeof(char_array3) << std::endl;
// *char_array3 is the first element of the array, it is a char, sizeof will return the char size allocated in memory: depends on your machine, normally is 1
std::cout << "sizeof(*char_array3):" << sizeof(*char_array3) << std::endl;
// *char_array3 is a char array, strlen will return the real content size of the string until '\0': 3
std::cout << "strlen(char_array3):" << strlen(char_array3) << std::endl;
std::cout << std::endl;
std::string str = {'a', 'b', '3', '\0', 'X'};
// str is a string, sizeof will return the string size allocated in memory (string is a wrapper, can be considered as a special structure with a pointer to the real content): depends on your machine, normally is 32
std::cout << "str:" << str << std::endl;
std::cout << "sizeof(str):" << sizeof(str) << std::endl;
// *str means nothing, sizeof will throw exeption
//std::cout << "sizeof(*str):" << sizeof(*str) << std::endl;
// str is a string, strlen will return the real content size of the string until '\0': 3
std::cout << "strlen(str):" << strlen(str.c_str()) << std::endl;
std::cout << std::endl;
// sizeof is an operation, if the parameter is a type, parentheses are mandatory
std::cout << "sizof(int):" << sizeof(int) << std::endl;
// sizeof is an operation, if the parameter is a variable, parentheses are optional
std::cout << "sizof char_star:" << sizeof char_star << std::endl;
std::cout << "sizof char_array:" << sizeof char_array << std::endl;
// sizeof is an operation, can take a function as parameter
std::cout << "sizeof(f()): " << sizeof(f1()) << std::endl;
std::cout << "sizeof(f()): " << sizeof(f2()) << std::endl;
}

Need help understanding pointer arithmetic

I'm having troubles understanding pointer arithmetic or how memory is assigned. In the code snippet below, I am trying to access the value of 'size = 1' which is located 8 bytes before 'test', but I don't get size's value and the value is not random. So I may have an issue with understanding bytes sizes. If void*, long, and char are 8 bytes should it matter when using pointer arithmetic?
#include <iostream>
using namespace std;
char arrayOfCrap[100];
void * what(){
long * size ;
size = (long*)&arrayOfCrap[28];
*size = 1;
return ((void*) &arrayOfCrap[29]);
}
int main(){
long * test;
test = (long*)what();
*test = 1221;
cout << "Value of test: " << *test << endl;
cout << "Long number before test: " << *(test-1) << endl;
}
The code works when main moves forward from what()'s void* 'pointer:
#include <iostream>
using namespace std;
char arrayOfCrap[100];
void * what(){
long * size ;
size = (long*)&arrayOfCrap[28];
*size = 1;
return ((void*) &arrayOfCrap[28]); //change from above
}
int main(){
long * test;
test = (long*)what();
test++; //change from above
*test = 1221;
cout << "Value of test: " << *test << endl;
cout << "Long number before test: " << *(test-1) << endl;
}
Your code is not locating *size eight bytes before *test:
size = (long*)&arrayOfCrap[28];
arrayOfCrap is char arrayOfCrap[100] so arrayOfCrap[28] is the char at offset 28 and arrayOfCrap[29] is the char at offset 29.
The reason test++ works is that test is of type long*, so incrementing it actually moves to the next position for a long, whereas incrementing a char* or using an index on a char array gives you the next position for a char.
You could also do one of these:
void * what(){
long * size ;
size = (long*)&arrayOfCrap[28];
*size = 1;
return size+1;
}
void * what(){
long * size ;
size = (long*)&arrayOfCrap[28];
*size = 1;
return ((void*) &arrayOfCrap[28 + sizeof(long)];
}
By the way, its not necessarily safe to take a pointer to just any memory location and treat it as a pointer to another type. Some platforms require some types to be 'aligned', or to have those types exist only at addresses that are multiples of a certain value. On those platforms reading or writing to an unaligned object may crash (bus error) or otherwise have undefined behavior. Also, some platforms may not crash or behave incorrectly, but have much better performance when reading/writing aligned objects. I know this is completely beside the point of your experimentation, but it's something you should know for real code. Here's an example of what not to do in real code:
int read_int(char *&c) {
int out = *(int*)c; // c may not be properly aligned!
c += sizeof(int);
return out;
}
Unfortunately on a common platform, x86, unaligned access is usually just slow rather than something that will always cause a crash, so users of that platform have to be especially careful.
When you increment a pointer, it increments not by the pointer size, but by the size of the type of the pointer. A char* pointer increments by sizeof(char), a long* pointer increments by sizeof(long)
sizeof(char *), sizeof(long *) should be both the same size (generally 4 bytes on 32-bit systems, 8 bytes on 64-bit systems).
However, sizeof(char) and sizeof(long) are not the same.
You are confusing your pointer size with the integer size.
#include <iostream>
using namespace std;
int main()
{
cout << "\n sizeof(char*) " << sizeof(char *);
cout << "\n sizeof(char) " << sizeof(char);
cout << "\n sizeof(long*) " << sizeof(long *);
cout << "\n sizeof(long) " << sizeof(long);
}
See it in action here: http://ideone.com/gBcjS