Print data of 2 variables using pointer in code below [closed] - c

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
I have the following code:
#include <stdio.h>
#include <stdlib.h>
int *p;
int main() {
int a = 4, b = 8;
p = &b;
//TODO: fill in the blank
printf("a = %ld\n", /*Fill in here */);
printf("b = %ld\n", /*Fill in here */);
return 0;
}
How can I print the value of 2 variables a and b using only p to access them?

In general, you cannot do this with current code /approach.
There's nothing in C standard that guarantees the memory allocation strategy for two or more independent variables, so the previous-next memory location tracking is not possible. There's no deterministic way to deduce the value of a, with only access to p.
In case you need to access values of more than one variables (of same type) from a single pointer, consider creating an array, where the elements are guaranteed to reside in contiguous memory location, so pointer arithmetic is meaningful and we can reach the previous-next element deterministically.

Related

Looking for answers to an old test that I took, trying to learn what I should have done.(Malloc Function Maybe?) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Old Test
I'm going over a test I took and am trying to figure out what the answer was to these questions. I was wondering if anyone could help me? As you can probably see I did not really understand how to answer them at the time but I would like to learn. I believed the answer has something to do with Malloc, but was unsure exactly how.
Thank you!
Edit : Is this how you do it?
#include <stdio.h>
#include <stdlib.h>
float* func();
int main(void)
{
float *x;
x = func();
printf("%f\n", *x);
return 0;
}
float* func(void){
float * z;
z = malloc(sizeof(float));
* z = 11.2;
return z;
}
malloc is related to allocating memory.
When we talk about array and pointer in c, we can seperate it into static array and dynamic array. For static array, we use array, for example,
char arr[10];
which means declare char type array named arr with length of 10.
For Dynamic array, we use pointer, for example, char *arr. This means char type pointer of arr. Pointer is very flexible; therefore, you must command to use it properly.
Assume
char *arr = (char *) malloc (sizeof (char) * 10);
This means you have a pointer and will allocate the memory with the size of char type with length of 10 you can also re allocate memory with realloc with different length. At the end of using it you must
free(arr);
To add, this is benefit of C language and I believe it is harder to use than other languages but more flexibility. On the other hand, you must be very very careful using it. Unproperly used pointer could cause entire software failure.
As float z is defined locally in fucntion, it's allocated on stack.
As a result it memory allocation is destroyed when function exits.
As a result you will have a runtime error cause you are accesing a memory that do not belongs to you.

Is this array possible in C? Is there any other way for it? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I declared an array in C of size 150X150X150. Upon compiling the program to get an array of same size,the compiler gave no errors or warnings. but when I tried running it, the program stops responding.
void main(){
int i,j,k;
char giv[150][150][50],tar[150][150][50];
for(int i=0;i<150;i++)
{
for(j=0;j<150;j++)
{
for(k=0;k<50;k++)
cin>>giv[i][j][k];
}
}
}
Is there any way that I can create an array of 150*150*150 without causing a run time error?
EDIT: I know multidimensional arrays work. This is not a compilation error. Its a run time error, whose cause was I am not able to pinpoint.
You just declared two arrays on the stack.
Each array has size: 150 * 150 * 50 bytes, or about 1.1MB.
So you are asking for 2.2MB from the stack.
Typical stack size is about 1 or 2MB.
So I expect you're getting a StackOverflow Exception.
(kinda appropriate for this site)
You could allocate the arrays on the heap:
#include <stdlib.h> /* for malloc()/calloc() */
#include <stdio.h> /* for perror() */
...
char (*pgiv)[150][150][50] = malloc(sizeof *giv);
char (*ptar)[150][150][50] = malloc(sizeof *tar);
If you want to have the arrays' elements initialised to all 0s on allocation use calloc() as follows:
char (*pgiv)[150][150][50] = calloc(1, sizeof *giv);
char (*ptar)[150][150][50] = calloc(1, sizeof *tar);
Also test wether the allocation succeed or not:
if (NULL == pgiv)
perror("malloc() failed");
if (NULL == ptar)
perror("malloc() failed");
Address an element by doing for example:
(*pgiv)[0][1][2] = 123;
Note that pgiv and ptar are actually pointers (to an array). That's why they need to be dereferenced (using the dereference operator *) before being used like an array.
It seems that the problem is with the limit of the stack memory.
In C++ you could use for example standard container std::vector.
In C you could allocate these arrays yourself dynamically.
The simplest way is either to declare these arrays globally that is outside any function or specify keyword static that the arrays had static storage duration. For example
static char giv[150][150][50],tar[150][150][50];
As for other languages then for example Java and C# allocate arrays in the managed heap. It keeps in the stack only a reference to the array.

typecasting a pointer to a multidimensional array in C [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
# include <stdio.h>
# include <stdlib.h>
int main(int argc, char *argv[])
{
int a[5][10][2];
int *p;
p = (int(*)[10][2])p;//Gives error!
return EXIT_SUCCESS;
}
I want to type cast p to type so that it can act as a pointer to the given 3-d array?Is there a way to do so.I am applyindg the idea that the type of a variable is everything except variable name.
Why are you trying to "typecast" anything? Why would you expect a value "typecasted" to (int(*)[10][2]) to be compatible with an int * pointer? And why does your original code assigns p to p, completely ignoring a?
This is what you can do
int a[5][10][2];
int (*p)[10][2] = a;
Now p is a pointer that can be used to access a, i.e. p[i][j][k] is equivalent to a[i][j][k]. No typecasting necessary.
If you write p = (int(*)[10][2])a; it won't give you any errors, may be a warning. You are thinking that p will be converted to pointer to a 3-D array, which is wrong. Try this statement after assigning a to p.
printf("addresses %u %u",p,p+1);
According to you, output should be something similar to this(lets say) "addresses 9990000 99940000", because you are thinking p is pointing to 3-D array. However you will get similar to "addresses 9990000 9990004", proving that p is a pointer to an integer.

This program output should be 11 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
#include<stdio.h>
#include<conio.h>
void main()
{
int *(intArray+3);
int i;
int (intArray+3)=&i;
*(intArray+3)=11;
printf("%d%d",i,*(intArray+3));
getch();
in this program i used the concept *(intArray+3)=intArray[3]
with base program
int *p;
int i;
p=&i;
*p=11;
printf("%d%d",i,*p);
in this case o/p is 11,11 but 1st program is based on this concept plez help?
The pointer arithmetic is possible only after defining and initializing a pointer. Now let me explain it:
Suppose there an array intArray of 5 elements ;
int intArray[5];
Let's assume the starting address of intArray is 2000. Now what (intArray + 3) does mean here? It means that (intArray + 3) is now referring to the fourth element (element 3) of the array intArray, i.e, now it is pointing to the location 2012 (as array name can be used as a pointer to its first element), assuming an int type is taking 4 bytes on a machine. When you place a * operator before it then it dereferences the value at that location, i.e, *(intArray + 3) will give you the value stored at the location 2012 which is equivalent to intArray[3].
Since you declared intArray neither as a pointer (for pointer it must be initialized) nor as an array, you can't dereference (intArray + 3). This is invalid and program will not compile.

C - pointers and change address [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have this code that gives a pointer an address and print it, but why that does not work??
void main()
{
int *b = (int*) 32;
printf("%d\n",b[0]);
}
b[0] dereferences an array which points to memory you haven't allocated. The effects of doing this are undefined. You might get a value returned or your program may crash if address 32 isn't readable from your process.
int *b = (int*) 32;
above code assigns memory address 32 to this pointer, i don't think that is you want, you will get access denied error when you call printf,
hope the following codes is useful toyou
int a = 32;
int *b = &a;
printf("%d\n",b[0]);
//output 32
printf( "%d\n", &b);
// output b pointer address.

Resources