Pointers predict the output - c++

#include <stdio.h>
void main (void){
int mat [5][5],i,j;
int *p;
p = &mat [0][0];
for (i=0;i<5;i++)
for (j=0;j<5;j++)
mat[i][j] = i+j;
printf ("%d\t", sizeof(mat)); i=4;j=5;
printf( "%d", *(p+i+j));
}
Can somebody help me with the output of this snippet . I get it the sizeof(mat) will print 50 . But help me with second printfc

*(p+i+j) will print the value stored at the address p + i*sizeof(int) + j*sizeof(j)
As array are stored in a linear way in the stack and i equals 4 and j equals 5 this will show the value of the 9th int of the array hence mat[1][4] which is equal to 5
Also for the result of sizeof(mat), it will be 5*5*sizeof(int). I assume here your int are stored on two bytes because you said it would print 50 but it totally depends on your computer. It is more usually 4 bytes long on todays computer so it could also print 100.

Try changing this second statement to:
printf("%d",*(p)+i+j );
I'm guessing you mean to print the sum of the value pointed at by p and the values stored in i and j

Related

setting char arrays equal to eachother with isdigit and isalpha

Im trying to set a char array equal to 2 other arrays depending on if the element in the first array is a number or a letter. The code makes logical sense to me but the output for the 2 other strings after the for loop doesn't correspond to the logic. Is it because of a missing null value somewhere in the other 2 loops or is the code itself invalid? arrayAlpha, arrayNum, and palind are all char arrays set to a length of 30 elements while string length was already determined before the for loop began.
for(int k=0; k<=stringLength; k++)
{
if( isalpha(palind[k])){
arrayAlpha[k]=palind[k];}
if ( isdigit(palind[k]))
{
arrayNum[k]=palind[k];
}
}
Given the input:
char palind[30] = "12345abcde";
arrayAlpha is garbage.
arrayNum is "12345"
However,
char palind[30] = "abcde12345";
arrayAlpha is "abcde".
arrayNum is garbage.
Thus, [k] is the problem when used in your arrayNum or arrayAlpha which doesn't start with 0.
Simple change will just be subtracting the length of the other.
arrayAlpha[k - strlen(arrayNum)] = palind[k];
arrayNum[k - strlen(arrayAlpha)] = palind[k];
since lengthOfPalind = lengthOfArrayAlpha + lengthOfArrayNum assuming palind only contains letters or numbers.

array getting more than it should

char name[4][20];
int count=0;
cout<<"Enter 4 name at most , one name per line:\n";
while(cin.getline(name[count++],20))
;
--count;
(rest of code is for printing if u need to see that too it's at the end)
when i Enter names more than 4 it still prints those names but how can that happen?
because the first dimension is 4 so how can it get more than four
printing part of code:
for(int i=0; i<count; i++)
{
cout<<i<<"="<<name[i]<<endl;
}
system("pause");
}
If I get it correctly, your are asking "why if the array is 4 I can fit 5?".
Unlike Pascal, where arrays boundaries are checked at runtime, C++ doens't do such thing.
Think about it. An array is just some pointer that is added the offset later.
Let's say that you've an array of 5 integers and you do this
int a[5];
a[3] = 3;
a[6] = 4;
Nothing is really wrong, because in the first assignment, the statement equals to a+12 and the second one a+24. You're just incrementing the pointer and unless you don't bother the OS, you could go on and potentially overwrite some other data.
So C++ will very unlikely say something if you cross the arrays boundaries.
This implies that you must always somehow know how big is the array, in your case by simply adding to the loop:
while(count < 4 && cin.getline(name[count++], 20));
You need to tell the while() loop when to stop.
Try this:
char name[4][20];
int count=0;
cout<<"Enter 4 name at most , one name per line:\n";
while(count < 4 && cin.getline(name[count++],20))
;

Array of pointer not giving proper output as it suppose?

Hi i have array of two pointers int *p[2] and i am trying to store 3 address of integer lets take &i,&j,&k as below code At *p[0]
i am getting garbage why here garbage ?it should be at p[2]? At *p[1] i am getting value it is ok but At *p[2] i am getting value here i should get garbage?
#include<stdio.h>
int main()
{
int i=10,j=20,k=30;
int *p[2]; // here p is array of 2 pointers
p[0]=&i; // but here i am storing
p[1]=&j; // 3 address of variable i,j,k
p[2]=&k;
printf("p[0]=%d\n",*p[0]); // why garbage here ?
printf("p[1]=%d\n",*p[1]); // here 20
printf("p[2]=%d\n",*p[2]); // here 30 why here ?
}
printf("p[2]=%d\n",*p[2]); // here 30 why here ?
Because p has two elements, not three. You can access elements 0 and 1, but accessing 2 is undefined behavior. Any number can be printed, or your program could crash when you invoke undefined behavior.
I am getting value here i should get garbage?
30 is as good a garbage value as any other number.
**EDIT (in response to an edit of the question) When you assign p[2] = &k you write to a location that is not allocated to your program. However, if the write operation completes without a crash, the new value would stay in memory.
Since the memory to which you wrote an address of k does not belong to your program, the system may write a new value into it. However, it wouldn't do it with 100% certainty: it may not write a new value into that memory at all. This is precisely what appears to be happening in your case: the value of &k written into p[2] illegally "survives" past two invocations of printf, producing 30 as the result.
u are using int *p[2], which is an array of size 2. only p[0] and p[1] are valid. remember the index of an array in c++ starts with 0 not 1. using p[2] would end up with something strange.
you are having array of two pointers int *p[2]. But you are trying to print the next element using pointer-
printf("p[2]=%d\n",*p[2]);
It results in undefined behavior. Anything can happen. But you are getting 30 some times you may get garbage values.
For your program i am getting-
root#ubuntu:~/c/array/string# ./a.out
p[0]=10
p[1]=20
p[2]=-13543595 // note this value. Undefined Behaviour
root#ubuntu:~/c/array/string#
first of all you need
int *p[3].
secondly since you used
int *p[2]
p[2] wasn't kept aside for this array. so what was there at p[2]? in my case it was variable k.
mine was 64 bit system with 64 bit pointers.
my output
p[0]=10
p[1]=20
p[2]=32767
and look at the gdb dump especially the addresses of k and p[2]
(gdb) p p[0]
$7 = (int *) 0x7fffffffe02c
(gdb) p p[1]
$8 = (int *) 0x7fffffffe028
(gdb) p p[2]
$9 = (int *) 0x7fffffffe024
(gdb) p &i
$10 = (int *) 0x7fffffffe02c
(gdb) p &j
$11 = (int *) 0x7fffffffe028
(gdb) p &k
$12 = (int *) 0x7fffffffe024
(gdb) p &p
$14 = (int *(*)[2]) 0x7fffffffe010
(gdb) x/32 0x7fffffffe010
0x7fffffffe010: -8148 32767 -8152 32767
0x7fffffffe020: -8156 32767 20 10
in your case it must have been the address of i.

converting integer into char explictly

I am trying to convert integer into character. I know how to convert character to integer like this int(a) where a is a character. But when I am trying to convert integer to character, it is giving me a symbolic value. Please help me out.
I am doing something like below. Thanks in advance.
int a=0;
char str1[20];
for(int i=0;i<size;i++)
//somecalculation that sets value in a everytime and stores in str1
str1[i]=char(a)-'A'
Well I am running for loop and setting values in str1. This is just little of my code.
You could use str1[i] = static_cast<char>(a + '0');. This will convert a = 0 to '0', a = 1 to '1' etc. Consider the behaviour as undefined outside the range 0, ..., 9.
just use sprintf:
for(int i=0;i<size;i++)
//somecalculation that sets value in a everytime and stores in str1
sprintf(str1 + i, "%i", a);
since you noted that a is each time only a one digit integer, this should work, but this is not very error prone... normally you should check on how much digits were written:
for(int i=0;i<size;i++)
//somecalculation that sets value in a everytime and stores in str1
if (sprintf(str1 + i, "%i", a) != 1)
printf("expected to print only one character!\n");

Initializing 2D int array in run-time

I got the code below from a C++ book, and I cannot figure out how the initialization works.
From what I can see, there is an outer for loop cycling trough the rows, and the inner loop
cycling trough the column. But its is the assignment of the values into the array that I do not understand.
#include <iostream>
using namespace std;
int main()
{
int t,i, nums[3][4];
for(t=0; t < 3; ++t) {
for(i=0; i < 4; ++i) {
nums[t][i] = (t*4)+i+1; //I don't understand this part/line
cout << nums[t][i] << ' ';
}
cout << '\n';
}
return 0;
}
so here are some questions.
I cannot understand the initialization of the 2D int array nums[3][4]. What separates the (t*4)+i+1, so that the compiler knows what to assign where?
How do I know what values will be stored in the rows and columns, based on what values have been assigned?
Why is there an asterisk?
What are the parentheses around t*4 for?
I understand that initialization two-dimensional arrays look like the following example.
#include <iostream>
using namespace std;
int main() {
char str[3][20] = {{"white" "rabbit"}, {"force"}, {"toad"}}; //initialize 2D character array
cout << str[0][0] << endl; //first letter of white
cout << str[0][5] << endl; //first letter of rabbit
cout << str[1][0] << endl; //first letter of force
cout << str[2][0] << endl; //first letter of toad
return 0;
}
And from what I know, like this in memory.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
0 w h i t e r a b b i t 0
1 f o r c e 0
2 t o a d 0
Thank you.
(t*4)+i+1
Is an arithmetic expression. t and i are ints, the * means multiply. So for row 1, column 2, t = 1, i = 2, and nums[1][2] = 1x4+2+1 = 7.
Oh, forgot a couple things. First, the () is to specify the order of operations. So the t*4 is done first. Note that in this case the () is unnecessary, since the multiply operator takes precedence over the plus operator anyway.
Also, I couldn't tell from your question if you knew this already or not, but the meaning of rows[t][i] is array notation for accessing rows at row t and column i.
For the first part, isn't it just assigning the a value equal to the row number * 4 plus the column number? I.E. the end result of the assignment should be:
1 2 3 4
5 6 7 8
9 10 11 12
So the expression (t*4)+i+1 means "4 multiplied by the row number plus the column number plus 1". Note that the row number and column numbers in this case start from 0.
nums[t][i] is the one spot in the array it is assigning the value of (t*4)+i+1.
So if t = 1 and i = 1 then the spot num[1][1] will equal (1*4)+1+1 which is 6.
See above.
Asterisk is for multiplying.
You do what's in the ( ) first just like in any mathematical equation.
Lets see, you have
int t,i, nums[3][4];
where we reserve space for the 2d array. The values inside the array will have random values since you only reserved space.
The line :
nums[t][i] = (t*4)+i+1; //I don't understand this part/line
Assigns the values to the array. You have t and i which are loop counters, and the line (t*4)+i+1 means, take value of t, multiply with 4, plus i and plus 1.
So for t=0, i =0, you get that nums[0][0] has value (0*4) + 0 + 1 which is 1.. etc for everything else.
And ofcourse the () are just basic math parentheses.