Using a Star Pointer in C

I asked the question: Skip array link using the C . I realized that my problem was to use a pointer star in C. And in the end, it turned out that this method works great for my program:

#include <stdio.h>

void FillArray(int** myArray)
{   
     *myArray = (int*) malloc(sizeof(int) * 2);

     (*myArray)[0] = 1;
     (*myArray)[1] = 2;
}

int main()
{
     int* myArray = NULL;
     FillArray(& myArray);  
     printf("%d", myArray[0]);
     return 0;
}

Everyone was fine until this moment. Then I changed the FillArray () function, as shown below, for better readability of the code:

#include <stdio.h>

void FillArray(int** myArray)
{
     int* temp = (*myArray);

     temp = (int*) malloc(sizeof(int) * 2);
     temp[0] = 1;
     temp[1] = 2;
}

int main()
{
     int* myArray = NULL;
     FillArray(& myArray);  
     printf("%d", myArray[0]);
     return 0;
}

Now I get the following runtime error on printf line:

The unhandled exception at 0x773115de in the Trial.exe file is: 0xC0000005: read access violation location 0x00000000.

Despite the fact that I am not an expert from C, it would seem legitimate to do this. However, this does not seem to work. Is the syntax a bit confusing? Am I missing something here?

Thanks for your helpful answers,

Sait.

+3
6

temp myArray, malloc ed temp, . malloc ed, myArray . myArray main,

*myArray = temp;

FillArray.

void FillArray(int** myArray)
{
     int* temp;
     temp = (int*) malloc(sizeof(int) * 2);
     temp[0] = 1;
     temp[1] = 2;
     *myArray = temp;
}

, .

+5

malloc'd , . , .

+1
int* temp = (*myArray);

temp - . , , .

temp = (int*) malloc(sizeof(int) * 2);  // Will not affect *myArray

-

void foo( int * ptr )
{
   ptr = malloc( sizeof(int) );
}

int *a ;
foo(a);   // Does `a` get allocated too ? NO.
0

:

#include <stdio.h>

void FillArray(int** myArray)
{
    (*myArray) = (int*) malloc(sizeof(int) * 2);
    (*myArray)[0] = 1;
    (*myArray)[1] = 2;
}

int main()
{
    int* myArray = NULL;
    FillArray(& myArray);  
    printf("%d\n", myArray[0]);
    printf("%d\n", myArray[1]);
    return 0;
}
0
int* temp = (*myArray);

, , .

de-reference myArray temp, int *, myArray is int **, - int *. , , , myArray , NULL, (* myArray), , myArray ( myArray NULL), , 0x00000000, NULL.

, , .

myArray ======> NULL

int* temp = (*myArray); //pointing temp to (*myArray)

myArray - NULL temp points no, , ,

myArray =======> NULL
temp =======> NULL

line 2 temp = (int *) malloc (sizeof (int) * 2);

Allocating the memory of two integers and indicating the tempo of the newly allocated memory so that the image becomes

myArray =======> NULL
temp =======> [ ] [ ]

the next two-line storage 1 and 2 in the 1st and 2nd memory cells, pointed to by temp

 temp[0] = 1;
 temp[1] = 2;

so now the image

myArray =======> NULL
temp =======> [1] [2]
0
source

Malloc temp before appointment!

-2
source

All Articles