Correct pointer arithmetic in C - c++

I am trying to learn pointer manipulation in C, and I am not understanding how part of the code isn't working.
#include <stdio.h>
int main() {
int *alpha[17];
*(alpha+4)= 35;
*(alpha+5)= 35;
*(alpha+12)= 50;
printf("%d", *(alpha+4));
*(alpha+8)=*(alpha+5) + *(alpha+12);
return 0;
}
Why is the line after the printf not working, and causing a crash, when the previous lines ran perfectly? I am trying to get the 9th value to equal the sum of the 6th and 13th value.

int *alpha[17]; creates array of pointers.
If you want array of int, use int alpha[17];
Your assignations are succesful because of implicit cast from int to pointer. (I hope you are getting warnings)
Adding two pointers is not only non-sensical, but also not allowed in C.
This post covers why adding two pointers is forbidden in C++, but arguiments are applicable to C also.

You have created an array of pointers but have not array of ints.
You should use:
int alpha[17];

Related

Creating links between arrays of pointers in C++?

how can I create links between two arrays of pointers in C++.
I (obviously) tried the method where I declared 2 pointer Arrays and started equating their indexes individually but C++ would give me an error (stating: cannot convert int* to int**).
So...any solutions?
For a better understanding of the question, look at this link:
QUESTION
EDIT:
Here's a simple breakdown code that I tried (but it didn't work at all):
#include<iostream>
using namespace std;
int main ()
{
int *A[4];
int *B[4];
A[0] = &B[1];
}
From the picture in your description, it seems that only elements of A need to point to elements of B. This means B can just be a regular array of ints:
int *A[4];
int B[4];
A[0] = &B[1];

I got a trouble with C++ array initialization

I am new to C++. Recently, I have been stuck with a simple code of C++ features. I will be very grateful if you can point out what exactly the problem. The code as follows:
// used to test function of fill
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
int val = 0;
int myarray[8];
//fill(myarray,myarray+2,1);
for(;val < 8;++val){
cout << myarray[val];
cout << endl;
}
}
And the it has printed out:
-887974872
32767
4196400
0
0
0
4196000
0
The question is I thought the default value for array without initialization (in this case its size is 8) would be (0,0,0,0,0,0,0,0). But there seemed to be some weird numbers there. Could anyone tell me what happened and why?
The elements are un-initialized, i.e, they contain garbage value.
If you want to initialize the array elements to 0, use this:
int myarray[8] = {};
Initial values are not guaranteed to be 0.
If you want to get a array have a initial value,you can do like this:
int *arr = new int[8]();
int myarray[8];
This is a simple declaration of an Array i.e you are telling the compiler "Hey! I am gonna use an integer array of size 8". Now the compiler knows it exists but it does not contail any values. It has garbage values.
If you intend to initialize array (automatically) then you need to add a blank initialization sequence.
int myarray[8]={}; //this will do
Happy Coding!

why does this fail

i am stuck and unable to figure out why this is the following piece of code is not running .I am fairly new to c/c++.
#include <iostream>
int main(){
const char *arr="Hello";
const char * arr1="World";
char **arr2=NULL;
arr2[0]=arr;
arr2[1]=arr1;
for (int i=0;i<=1;i++){
std::cout<<arr2[i]<<std::endl;
}
return 0;
}
where as this is running perfectly fine
#include <iostream>
int main(){
const char *arr="Hello";
const char * arr1="World";
char *arr2[1];
arr2[0]=arr;
arr2[1]=arr1;
for (int i=0;i<=1;i++){
std::cout<<arr2[i]<<std::endl;
}
return 0;
}
Why is this? and generally how to iterate over a char **?
Thank You
char *arr2[1]; is an array with one element (allocated on the stack) of type "pointer to char". arr2[0] is the first element in that array. arr2[1] is undefined.
char **arr2=NULL; is a pointer to "pointer to char". Note that no memory is allocated on the stack. arr2[0] is undefined.
Bottom line, neither of your versions is correct. That the second variant is "running perfectly fine" is just a reminder that buggy code can appear to run correctly, until negligent programming really bites you later on and makes you waste hours and days in debugging because you trashed the stack.
Edit: Further "offenses" in the code:
String literals are of type char const *, and don't you forget the const.
It is common (and recommended) practice to indent the code of a function.
It is (IMHO) good practice to add spaces in various places to increase readability (e.g. post (, pre ), pre and post binary operators, post ; in the for statement etc.). Tastes differ, and there is a vocal faction that actually encourages leaving out spaces wherever possible, but you didn't even do that consistently - and consistency is universially recommended. Try code reformatters like astyle and see what they can do for readability.
This is not correct because arr2 does not point to anything:
char **arr2=NULL;
arr2[0]=arr;
arr2[1]=arr1;
correct way:
char *arr2[2] = { NULL };
arr2[0]=arr;
arr2[1]=arr1;
This is also wrong, arr2 has size 1:
char *arr2[1];
arr2[0]=arr;
arr2[1]=arr1;
correct way is the same:
char *arr2[2] = { NULL };
arr2[0]=arr;
arr2[1]=arr1;
char **arr2=NULL;
Is a pointer to a pointer that points to NULL while
char *arr2[1];
is an array of pointers with already allocated space for two items.
In the second case of the pointer to a pointer you are are trying to write data in a memory location that does not exist while in the first place the compiler has already allocated two slots of memory for the array so you can assign values to the two elements.
If you think of it very simplistically, a C pointer is nothing but an integer variable, whose value is actually a memory address. So by defining char *x = NULL you are actually defining a integer variable with value NULL (i.e zero). Now suppose you write something like *x = 5; This means go to the memory address that is stored inside x (NULL) and write 5 in it. Since there is no memory slot with address 0, the the entire statement fails.
To be honest it;s been ages since I last had to deal with such stuff however this little tutorial here, might clear the motions of array and pointers in C++.
Put simply the declaration of a pointer does NOT reserve any memory, where as the declration of a array doesn't.
In your first example
Your line char **arr2=NULL declares a pointer to a pointer of characters but does not set it to any value - thus it is initiated pointing to the zero byte (NULL==0). When you say arr2[0]=something you are attempting to place a valuei nthis zero location which does not belong to you - thus the crash.
In your second example:
The declaration *arr2[2] does reserve space for two pointers and thus it works.

Pointer to int array, passing and using it from another method

I haven't cemented my learning of C++ arrays and have forgotten how to do this properly. I've done it with char array before but its not working as well for int array.
I declare a new blank int array:
int myIntArray[10];
So this should be an array of nulls for the moment correct?
Then I assign a pointer to this array:
int *pMyArray = myIntArray
Hopefully thats correct to there.
Then I pass this to another method elsewhere:
anotherMethod(pMyArray)
where I want to assign this pointer to a local variable (this is where I'm really not sure):
anotherMethod(int *pMyArray){
int myLocalArray[];
myLocalArray[0] = *pMyArray;
}
I'm not getting any compilation errors but I'm not sure this is right on a few fronts. Any and all help and advice appreciated with this.
Edit:
I should have said what I am trying to do.
Very simple really, I'd just like to modify a local array from another method.
So I have:
Method 1 would contain:
int myArray1[10] = {0};
Method 2 would be passed the pointer to myArray:
Then some code to modify the variables in the array myArray.
int myIntArray[10];
This is an uninitialized array. It doesn't necessarily contain 0's.
int *pMyArray = myIntArray
Okay, pMyArray points to the first element in myIntArray.
anotherMethod(int *pMyArray){
int myLocalArray[10];
myLocalArray[0] = *pMyArray;
}
This doesn't assign your pointer to anything, it assigns the first value of the local array to the int pointed to by pMyArray, which, remember, was uninitialized. I added the 10 there because you can't have an array of unknown size in C++.
To modify what pMyArray points to, you need to pass it by reference:
anotherMethod(int *& pMyArray)
Also, if you assign it to some values in automatic storage, it will result in undefined behavior, as that memory is no longer valid when the function exits.
int myIntArray[10];
So this should be an array of nulls for the moment correct?
No, this is an array of 10 integers containing values depending on the storage specification.
If created locally, it has random garbage values.
If created globally it is value initialized which is zero initialized for POD.
Besides that your method just assigns the local array with the first vale of the array you pass.
What are you trying to do exactly? I am not sure.
int myIntArray[10];
So this should be an array of nulls for the moment correct?
Not correct, it is an array of 10 uninitialized ints.
int *pMyArray = myIntArray
Hopefully thats correct to there.
Not quite correct, pMyArray is a pointer to the 1st element, myIntArray[0].
where I want to assign this pointer to a local variable (this is where
I'm really not sure):
If you really need to assign the pointer, you have to use this code
int *p_myLocalArray;
p_myLocalArray = pMyArray;
There are a few mistakes here.
First, array of zeros (not nulls) is achieved by using the initializer syntax:
int myIntArray[10] = {0};
Second, int myLocalArray[]; has a size of 0. And even if it did have a size of, say, 10, writing myLocalArray[0] = *pMyArray; will assign the first int from pMyArray into mLocalArray, which is not what you meant.
If you want to assign a pointer of the array, then simply:
int *myLocalPointer;
myLocalPointer = pMyArray;
If you want a local copy of the array, you will need to copy it locally, and for that you also need the size and dynamic allocation:
void anotherMethod(int *pMyArray, int size){
int *myLocalArray = (int *)malloc(size * sizeof(int));
memcpy(myLocalArray, pMyArray, size * sizeof(int));
...
free(myLocalArray);
}

Dereferencing pointer to array when debugging in XCode 4.2

I'm using XCode to follow along in an intro to programming C++ class. No grade involved, I'm simply living vicariously through the eyes of others. Now that we've reached the subject of pointers I'm having trouble keeping track of where I am. If I pass a pointer to a dynamic array into a function how can I dereference that pointer to see what's actually being held in the various positions of the array. My code is compiling, but a couple of the functions are returning garbage. A clear indication that something isn't point to the right place.
Thanks in advance!
--John
It's likely that some code will be needed to further understand your problem, but from what I understood, here is what you need.
#include <iostream>
void f(int *array){
std::cout<<array[5];
}
int main(){
int* array = new int[10];
array[5] = 20;
f(array);
return 0;
}
This will print "20".