answersLogoWhite

0


Best Answer

For the purpose of clarification, you cannot initialise types, you can only initialise variables (or constants) of a type. A variable (or constant) is known as an "instance" or "object" of the type. All instances of a type must be named. A pointer variable allows us to "refer" to a named object of the pointer's type. this is achieved by storing the memory address (the starting address) of that object. By changing the address stored in the pointer variable, the same pointer variable can be used to refer to different objects in memory. This is useful when passing objects to functions because if we pass objects directly (by name), the function receives a copy of the object. This is known as "pass by value". However, when a function expects a pointer variable rather than a named variable, the address of the object is copied instead. This is known as "pass by reference" and allows the function to operate (indirectly) upon the object being referenced rather than a copy of the object (any changes to a copy are not reflected in the original object).

Passing by reference is particularly useful when the object is large and complex. To improve efficiency, we must avoid making any unnecessary copies of large or complex objects. Functions that do not modify an object are a prime example; there is no point in copying an object that will not be modified. If we wish a function to modify the object, we must pass the object by reference. The only time we should copy an object is when we're not interested in the modifications made by a function, or when we want to compare the changes that were made. In these cases we simply make a copy of the object before passing that copy to the function by reference. When working with concurrency, however, it is best to use pass by value semantics. In this way, each thread works with a local copy of your object, and thus avoids "race conditions", where one task is accessing an object that is being modified by another task, which can lead to unpredictable results.

Pointer variables are said to "point at" the memory the refer to (hence they are called pointers). To access the value being pointed at, the pointer variable must be dereferenced. However, in the case of pointer to struct variables, the dereferencing is transparent.

All variables in Go are implicitly initialised with the default "zero" value for its type. The zero value of a pointer variable is always "nil" (regardless of which type of pointer). You must never dereference a pointer variable that holds the nil value so always check the pointer is non-nil. Equally, you must never dereference a pointer to an object that no longer exists in memory. Always nil your pointers as soon as you are finished with them.

The following example demonstrates how to initialise a pointer variable to a struct:

package main

import "fmt"

type Point struct {

X int

Y int

}

func main () {

v := Point{1, 2} // instantiate an object of type Point

p := &v // assign the address of v to pointer p (p's type is inferred from v)

fmt.Println(*p) // print the indirect value of v (dereference p)

}

User Avatar

Wiki User

9y ago
This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: How can I initialize a type that is a pointer to a struct in Go?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering

Write a c program to insert an element in the beginning at the end at the specified position in a linear linked list?

#include<stdio.h> #include<stdlib.h> typedef struct Node { int data; struct Node *next; }node; void insert(node *pointer, int data) { /* Iterate through the list till we encounter the last node.*/ while(pointer->next!=NULL) { pointer = pointer -> next; } /* Allocate memory for the new node and put data in it.*/ pointer->next = (node *)malloc(sizeof(node)); pointer = pointer->next; pointer->data = data; pointer->next = NULL; } int find(node *pointer, int key) { pointer = pointer -> next; //First node is dummy node. /* Iterate through the entire linked list and search for the key. */ while(pointer!=NULL) { if(pointer->data == key) //key is found. { return 1; } pointer = pointer -> next;//Search in the next node. } /*Key is not found */ return 0; } void delete(node *pointer, int data) { /* Go to the node for which the node next to it has to be deleted */ while(pointer->next!=NULL && (pointer->next)->data != data) { pointer = pointer -> next; } if(pointer->next==NULL) { printf("Element %d is not present in the list\n",data); return; } /* Now pointer points to a node and the node next to it has to be removed */ node *temp; temp = pointer -> next; /*temp points to the node which has to be removed*/ pointer->next = temp->next; /*We removed the node which is next to the pointer (which is also temp) */ free(temp); /* Beacuse we deleted the node, we no longer require the memory used for it . free() will deallocate the memory. */ return; } void print(node *pointer) { if(pointer==NULL) { return; } printf("%d ",pointer->data); print(pointer->next); } int main() { /* start always points to the first node of the linked list. temp is used to point to the last node of the linked list.*/ node *start,*temp; start = (node *)malloc(sizeof(node)); temp = start; temp -> next = NULL; /* Here in this code, we take the first node as a dummy node. The first node does not contain data, but it used because to avoid handling special cases in insert and delete functions. */ printf("1. Insert\n"); printf("2. Delete\n"); printf("3. Print\n"); printf("4. Find\n"); while(1) { int query; scanf("%d",&query); if(query==1) { int data; scanf("%d",&data); insert(start,data); } else if(query==2) { int data; scanf("%d",&data); delete(start,data); } else if(query==3) { printf("The list is "); print(start->next); printf("\n"); } else if(query==4) { int data; scanf("%d",&data); int status = find(start,data); if(status) { printf("Element Found\n"); } else { printf("Element Not Found\n"); } } } }


Why must the stack pointer be initialized at the beginning of every program?

Because the stack pointer marks the top of the stack. If it is not initialised, it is not possible to determine where the next stack frame will go.


Can you use business logic in constructor with example in java?

No. Logic should never go in a constructor; constructors should only be used to instantiate and initialize object data.


What is const pointer?

In computer science, const-correctness is the form of program correctness that deals with the proper declaration of objects as mutable or immutable. The term is mostly used in a C or C++ context, and takes its name from the const keyword in those languages. The idea of const-ness does not imply that the variable as it is stored in the computer's memory is unwriteable. Rather, const-ness is a compile-time construct that indicates what a programmer may do, not necessarily what he or she can do. In addition, a class method can be declared as const, indicating that calling that method does not change the object. Such const methods can only call other const methods but cannot assign member variables. (In C++, a member variable can be declared as mutable, indicating that a const method can change its value. Mutable member variables can be used for caching and reference counting, where the logical meaning of the object is unchanged, but the object is not physically constant since its bitwise representation may change.) In C++, all data types, including those defined by the user, can be declared const, and all objects should be unless they need to be modified. Such proactive use of const makes values "easier to understand, track, and reason about," and thus, it increases the readability and comprehensibility of code and makes working in teams and maintaining code simpler because it communicates something about a value's intended use. For simple data types, applying the const qualifier is straightforward. It can go on either side of the type for historical reasons (that is, const char foo = 'a'; is equivalent to char const foo = 'a';). On some implementations, using const on both sides of the type (for instance, const char const) generates a warning but not an error. For pointer and reference types, the syntax is slightly more subtle. A pointer object can be declared as a const pointer or a pointer to a const object (or both). A const pointer cannot be reassigned to point to a different object from the one it is initially assigned, but it can be used to modify the object that it points to (called the "pointee"). (Reference variables are thus an alternate syntax for const pointers.) A pointer to a const object, on the other hand, can be reassigned to point to another object of the same type or of a convertible type, but it cannot be used to modify any object. A const pointer to a const object can also be declared and can neither be used to modify the pointee nor be reassigned to point to another object. The following code illustrates these subtleties: void Foo( int * ptr, int const * ptrToConst, int * const constPtr, int const * const constPtrToConst ) { *ptr = 0; // OK: modifies the pointee ptr = 0; // OK: modifies the pointer *ptrToConst = 0; // Error! Cannot modify the pointee ptrToConst = 0; // OK: modifies the pointer *constPtr = 0; // OK: modifies the pointee constPtr = 0; // Error! Cannot modify the pointer *constPtrToConst = 0; // Error! Cannot modify the pointee constPtrToConst = 0; // Error! Cannot modify the pointer To render the syntax for pointers more comprehensible, a rule of thumb is to read the declaration from right to left. Thus, everything before the star can be identified as the pointee type and everything to after are the pointer properties. (For instance, in our example above, constPtrToConst can be read as a const pointer that refers to a const int.) References follow similar rules. A declaration of a const reference is redundant since references can never be made to refer to another object: int i = 42; int const & refToConst = i; // OK int & const constRef = i; // Error the "const" is redundant Even more complicated declarations can result when using multidimensional arrays and references (or pointers) to pointers. Generally speaking, these should be avoided or replaced with higher level structures because they are confusing and prone to error.


What if the storage address and content both have the same value?

It means your program has undefined behaviour. In weakly-typed languages such as C it is very easy to assign a pointer to itself but in strongly-typed languages such as C++, the type system prevents it. However, we can use a C-style cast to circumvent the type system. Consider the following example: #include<iostream> int main() { // Declare a pointer variable. int* p; // Assign the pointer's address to itself using a C-style cast. p = (int*)&p; // Print the address of the pointer. std::cout << "Pointer address:\t0x" << &p << std::endl; // Print the pointer's value. std::cout << "Pointer value:\t\t0x" << p << std::endl; // Print the dereferenced value. std::cout << "Dereferenced value:\t" << *p << std::endl; // Assign a value to the address being pointed at. *p = 42; } The exact address of the pointer will vary, but the output may be something like the following: Pointer address: 0x0072FB48 Pointer value: 0x0072FB48 Dereferenced value: 7535432 The first two lines of output prove the pointer really does point to itself (the storage address and its content have the same value). The third line also proves that the pointer can be correctly dereferenced (7535432 is the decimal equivalent of 0x0072FB48). Everything appears to work normally, but the final line of code has actually violated the type system: *p = 42; Think about what we're doing here. We're assigning the value 42 to the address pointed to by p. But p points to itself, thus p now holds the value 42 and is therefore pointing at memory address 42 (0x0000002A). That's clearly not what we intended but, by undermining the type safety, such errors are only inevitable. Even if memory address 42 belongs to our program, a 4-byte integer would be expected to be aligned on a 4-byte boundary but 42 is clearly not a 4-byte boundary. Our program doesn't actually make any attempt to access address 42, so no errors will be reported. However, if this code were part of a much larger program we'd be in a whole world of hurt because it may not be immediately obvious that a problem exists until we try to dereference that pointer, which may be a long time after we assigned the value. That's a time-bomb waiting to go off! There's also the problem of what happens when the type being pointed at is larger than that of the pointer itself. If we attempt to assign a value that will not fit inside a pointer then we'd end up overwriting memory that doesn't actually belong to the pointer. Either way we introduce undefined behaviour. Even if our program appears to work as intended (as in the example above), it makes no sense to deliberately undermine a system that is intended to prevent such problems arising in the first place.

Related questions

How do you change the shape of the pointer?

Start -> Settings -> Control Panel -> Mouse -> Select "Pointer" tab and go to customise and choose the desired pointer


How do you change your computers cursor for Windows 8?

go to the start menu and type in mouse and press enter. at the near top of the window click on the pointer tab. then a drop down box Will appear saying pointer scheme beside it.


How far can a 5mw laser pointer go?

10 ft


How far does a 1mW laser pointer go?

200 miles


Write a c program to insert an element in the beginning at the end at the specified position in a linear linked list?

#include<stdio.h> #include<stdlib.h> typedef struct Node { int data; struct Node *next; }node; void insert(node *pointer, int data) { /* Iterate through the list till we encounter the last node.*/ while(pointer->next!=NULL) { pointer = pointer -> next; } /* Allocate memory for the new node and put data in it.*/ pointer->next = (node *)malloc(sizeof(node)); pointer = pointer->next; pointer->data = data; pointer->next = NULL; } int find(node *pointer, int key) { pointer = pointer -> next; //First node is dummy node. /* Iterate through the entire linked list and search for the key. */ while(pointer!=NULL) { if(pointer->data == key) //key is found. { return 1; } pointer = pointer -> next;//Search in the next node. } /*Key is not found */ return 0; } void delete(node *pointer, int data) { /* Go to the node for which the node next to it has to be deleted */ while(pointer->next!=NULL && (pointer->next)->data != data) { pointer = pointer -> next; } if(pointer->next==NULL) { printf("Element %d is not present in the list\n",data); return; } /* Now pointer points to a node and the node next to it has to be removed */ node *temp; temp = pointer -> next; /*temp points to the node which has to be removed*/ pointer->next = temp->next; /*We removed the node which is next to the pointer (which is also temp) */ free(temp); /* Beacuse we deleted the node, we no longer require the memory used for it . free() will deallocate the memory. */ return; } void print(node *pointer) { if(pointer==NULL) { return; } printf("%d ",pointer->data); print(pointer->next); } int main() { /* start always points to the first node of the linked list. temp is used to point to the last node of the linked list.*/ node *start,*temp; start = (node *)malloc(sizeof(node)); temp = start; temp -> next = NULL; /* Here in this code, we take the first node as a dummy node. The first node does not contain data, but it used because to avoid handling special cases in insert and delete functions. */ printf("1. Insert\n"); printf("2. Delete\n"); printf("3. Print\n"); printf("4. Find\n"); while(1) { int query; scanf("%d",&query); if(query==1) { int data; scanf("%d",&data); insert(start,data); } else if(query==2) { int data; scanf("%d",&data); delete(start,data); } else if(query==3) { printf("The list is "); print(start->next); printf("\n"); } else if(query==4) { int data; scanf("%d",&data); int status = find(start,data); if(status) { printf("Element Found\n"); } else { printf("Element Not Found\n"); } } } }


How do you use remote desktop connection with a computer on your network?

Go in start, in start menu all programs then accessories in accessories bring pointer on communication, in communication bring pointer on remote desktop connection afterclicking on remote desktop connection , Type computer name or ip address of neighbour computer then type user name and password of neighbour computer.


What nicknames does Ron Genta go by?

Ron Genta goes by Pointer.


How do you get mouse pointers on a computer?

Well, first you click on " Start ". then you go to Control Panel. You right click "Mouse" then you go to pointer options then you click on Display Pointer Trails. At the bottom, you can control the speed.


How can you get a 3d bronze mouse pointer?

go to control panel. then click on sound and hardware. click pointer appearance,then click 3d bronze cursor icon


Why must the stack pointer be initialized at the beginning of every program?

Because the stack pointer marks the top of the stack. If it is not initialised, it is not possible to determine where the next stack frame will go.


Do You can change the appearance of the mouse pointer true or false?

True if using windows XP. Go to control panel. Double left click the mouse icon. Select Pointer from the top menu bar. This gives you many alternative pointer options.


What make the mouse pointer change to an eyedropper?

go 2 da control panel in start