#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int * p = malloc(sizeof(int));
*p = 10;
*p += 10;
printf("%d", *p);
}
It gives me the correct value if it is malloc'd but a bus error if I just declare it as:
int main(){
int * p;
*p = 10;
*p += 10;
printf("%d", *p);
}
An uninitialized pointer is just that; uninitialized. Where do you expect it to point? It's value is indeterminate and reading/writing it results in undefined behavior.
It doesn't have to refer to dynamically allocated memory (malloc), but it does have to refer to valid memory. For example, this would be fine:
int main(void)
{
int x;
int *p = &x;
*p = 10;
*p += 10;
printf("%d", *p);
}
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr;
//*ptr=123; Error here....Becuase it is like trying to store
//some thing into a variable without creating it first.
ptr=malloc(sizeof(int)); // what malloc does is create a integer variable for you
// at runtime and returns its address to ptr,
// Which is same as if you assingned &some_variable
// to ptr if it had been already present in your program.
return 0;
}
Related
I'm trying to change the x value in this code but I'm getting segmentation fault.
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int **x;
} Type;
int main() {
int a = 1;
Type *type = malloc(sizeof(Type));
type->x[0] = &a;
return 0;
}
if you want an array of pointers to ints
int main() {
int a = 1;
Type *type = malloc(sizeof(Type));
type->x = malloc(sizeof(int*) * 10)) ;// say we need 10
type->x[0] = &a;
return 0;
}
I have this code:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
void ft_ultimate_ft(int *********nbr)
{
printf("%d", *********nbr);
}
int main(){
/*Start of problem*/
int *a;
int **b = &a;
int ***c = &b;
int ****d = &c;
int *****e = &d;
int ******f = &e;
int *******g = &f;
int ********h = &g;
int *********i = &h;
/*end of problem*/
*********i = 42;
ft_ultimate_ft(i);
return 0;
}
I need to include pointer-to-pointer declaration in the loop (for example, while). It's needed to decrease number of declarations.
I am assuming that I have properly understood you question, which is to create a multiple pointer to a number using a loop and then assign value to it.
I wrote a piece of code that partly completes your requirement but still need to know how many layers there are after the loop.
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
void ft_ultimate_ft(int *********nbr)
{
printf("%d", *********nbr);
}
int main() {
int t = 10;
int n = 8;
void * p = &t;
for (int i = 0; i < n; i++)
{
void* * s = (void **)malloc(sizeof(void*));
*s = p;
p = s;
}
/*end of problem*/
int *********real = (int *********)p;
*********real = 42;
ft_ultimate_ft(real);
return 0;
}
Which outputs 42
The clean up part of the program is not written
PS. In your code, the pointer a is indeterminate and I do not think that your original code can work properly.
int foo(int *p){
p = malloc(sizeof(int));
*p = 20;
}
int main(){
int a;
int *x;
x = &a;
foo(x);
printf("%d \n", a);
return 0;
}
So I'm trying to point at a and then set the value of what x is pointing to 20. However whenever I allocate the pointer in the function I get a random number being printed. Do you know why this happens compared to allocating it in main()?
Thanks
You don't want to allocate in the foo function at all. This is like doing:
void foo(int p) {
p = 2;
printf("%d\n", p);
}
int main() {
int a=1;
foo(a);
return 0;
}
And asking why it didn't print 1. The answer is, you're writing over the pointer to a, so you no longer have a pointer to a when you do *p = 20;.
So I'm trying to point at a and then set the value of what x is pointing to 20
This doesn't make sense given the context of your question. You are pointing x at a, and if you want to change the value of a, then why are you dynamically allocating anything at all? a is already automatically allocated in main(). If you want to dynamically allocate something, what you you need a for at all?
To change the value of a, just pass a pointer to it and forget about malloc():
void foo(int * p)
{
*p = 20;
}
int main(void)
{
int a;
foo(&a);
printf("%d\n", a);
return 0;
}
If you want to dynamically allocate, forget about a, and don't modify it through a passed pointer - return the pointer:
int * foo(void)
{
int * p = malloc(sizeof *p);
if ( !p ) {
perror("could not allocate memory");
exit(EXIT_FAILURE);
}
*p = 20;
return p
}
int main(void)
{
int * x = foo();
printf("%d\n", *x);
free(x);
return 0;
}
I know you can return a type of pointer from a function.
ex. void *foo()
Can you return a type of pointer to pointer in a function?
ex. void **foo2()
Here is more info about my question:
I try to assign a ptr-to-ptr, tmp2, to blocks[i][j], and then return tmp2. blocks[i][j] is a ptr-to-ptr as well.
I'm confused to manipulate a ptr to a ptr-to-ptr: I am not sure if return ((tmp2+i)+j); is the cause of the segmentation fault at line printf("2---%d\n", **tmpPtr2);. To debug, I try to print: printf("%d\n", *( (*(tmp2+i)) +j) ); However, it causes a new segmentation fault.
#include <stdio.h>
#include <stdlib.h>
int **blocks, **tmp2;
int n = 10;
int **findBlock2(int b){
int i, j ;
for (i=0; i<n; i++){
for (j=0; j<n; j++){
if (blocks[i][j]==b){
printf("%d\n", blocks[i][j]);
//Segmentation fault
printf("%d\n", *((*(tmp2+i))+j) );
return ((tmp2+i)+j);
}
}
}
return NULL;
}
int main(int argc, const char * argv[]) {
int i, j;
int **tmpPtr2;
//allocate memory space and assign a block to each index
blocks=malloc(n * sizeof *blocks);
for (i=0; i<n; i++) {
blocks[i]=malloc(n * sizeof(*blocks[i]));
blocks[i][0]=i;
}
if ((tmpPtr2=findBlock2(4))==NULL) return -1;
//Segmentation Fault
printf("2---%d\n", **tmpPtr2);
return 0;
}
Update to answer my question:
(1) Adding ttmp2=blocks; to the top of findBlock2() removed both segfaults.
(2) return ((tmp2+i)+j); shows how to manipulate a ptr-to-ptr pointing to a ptr-to-ptr or a 2D array
(3) printf("%d\n", *( (*(tmp2+i)) +j) ); shows how to do (2) and dereference it.
Hope it helps others
Yeah, just like you would with any pointer variables.
#include <stdio.h>
#include <stdlib.h>
int ** function(){
int ** matrix = malloc(sizeof(int*));
*matrix = malloc(sizeof(int));
matrix[0][0] = 5;
return matrix;
}
int main()
{
int **matrix = function();
printf("%d",matrix[0][0]);
free(matrix[0]);
free(matrix);
return 0;
}
Adding to the other part. In your function findBlock2 besides accessing an invalid reference that has already been pointed out, it seems that your objective is to return a reference to the block that fulfills if statement. If that is the case then returning a pointer to int* should suffice.
int *findBlock2( int b )
/////////////////
return ( *(blocks+i)+j );
You probably want a 2D array at not some slow, fragmented lookup table. In that case, do like this:
#include <stdlib.h>
void* alloc_2D (size_t x, size_t y)
{
return malloc (sizeof (int[x][y]));
}
int main (void)
{
const size_t X = 5;
const size_t Y = 3;
int (*arr_2D)[Y] = alloc_2D(X, Y);
// X dimension was omitted in declaration to make array syntax more intuititve:
arr_2D[i][j] = something;
...
free(arr_2D);
}
The answer is "yes". Please refer the following code:
#include <stdio.h>
#include <malloc.h>
void ** foo2(void){
int **p = malloc(sizeof(*p));
return (void**)p;
}
int main(void) {
printf("%p\n", foo2());
return 0;
}
The result is (in my 32-bit platform):
0x80e9008
The following code gives a segmentation fault. I am not able to figure out as to why. Please see..
#include <stdio.h>
#include <stdlib.h>
int main()
{
int **ptr;
int *val;
int x = 7;
val = &x;
*ptr = (int *)malloc(10 * sizeof (*val));
*ptr[0] = *val;
printf("%d\n", *ptr[0] );
return 0;
}
on debugging with gdb, it says:
Program received signal SIGSEGV, Segmentation fault.
0x0804843f in main () at temp.c:10
*ptr = (int *)malloc(10 * sizeof (*val));
Any help regarding the matter is appreciated.
int **ptr;
*ptr = (int *)malloc(10 * sizeof (*val));
First statement declares a double pointer.
Second dereferences the pointer. In order that you are able to dereference it the pointer should point to some valid memory. it does not hence the seg fault.
If you need to allocate enough memory for array of pointers you need:
ptr = malloc(sizeof(int *) * 10);
Now ptr points to a memory big enough to hold 10 pointers to int.
Each of the array elements which itself is a pointer can now be accessed using ptr[i] where,
i < 10
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int **ptr;
int x;
x = 5;
ptr = malloc(sizeof(int *) * 10);
ptr[0] = &x;
/* etc */
printf("%d\n", *ptr[0]);
free(ptr);
return 0;
}
See the below program, perhaps, it helps to understand better.
#include<stdio.h>
#include <stdlib.h>
int main(){
/* Single Dimention */
int *sdimen,i;
sdimen = malloc ( 10 * sizeof (int));
/* Access elements like single diminution. */
sdimen[0] = 10;
sdimen[1] = 20;
printf ("\n.. %d... %d ", sdimen[0], sdimen[1]);
/* Two dimention ie: **Array of pointers.** */
int **twodimen;
twodimen = malloc ( sizeof ( int *) * 10);
for (i=0; i<10; i++) {
twodimen[i] = malloc (sizeof(int) * 5);
}
/* Access array of pointers */
twodimen[0][0] = 10;
twodimen[0][3] = 30;
twodimen[2][3] = 50;
printf ("\n %d ... %d.... %d ", twodimen[0][0], twodimen[0][3], twodimen[2][3]);
return 0;
}
Hope this helps.. ;).
Conceptually if you are using **ptr, then you need to alloacte memory for ptr & *ptr to defrence **ptr.
But in you case you are alloacting memory only for *ptr,if your compiler is smart enough
its alloacting memory for ptr(one pointer location) to link *ptr,hence it could able to link ptr->ptr->*ptr.Hence you are not getting Seg Fault.
include
include
int main()
{
int **ptr;
int *val;
int x = 7;
val = &x;
ptr = (int**)malloc(sizeof(int**));
*ptr = (int *)malloc(10 * sizeof (*val));
*ptr[0] = *val;
printf("%d\n", *ptr[0] );
return 0;
}
Above would work.
You can find the difference and understand the reason as well.
Bottom line you were de-referencing **ptr without allocating memory to it.