My question may be unclear but, can integer pointers be in any type of data structure? I mean like in a list, tree, graph, etc.

Like say a linked list:

struct list
{
 struct list *next;
 int *some_data;
}

Certainly! This is not uncommon. However, it would be preferable in your example to use a non-pointer-to-integer. Why? Because you don't have control over that pointer. The code that set it may delete it, then where are you? In SEGFAULT land! As a software developer, you need to think about this stuff, all the time! Figure that the users will do stuff that will bork the system. Your job is to minimize the possibility that their actions will compromise the system. This plays directly into security considerations as well.

I don't know what your really saying. That will help if that was a yes or no. So, I guess what your saying is no integer pointers can't be in a list structure from my example. I do know that pointers can be a structure variable that points to a variable or what ever structure variables point to in the list from my example.

No, I simply said that doing so is not safe coding practice. In itself, that is workable, but before you try to access the contents of the pointer (the real integer), you need to be sure that it isn't null. When you allocate those structures you should use calloc() and not malloc() as that will clear the memory, making sure that both pointers are set to NULL and not some bogus address. Consider this code:

struct list
{
    struct list* next;
    int* data;
};

struct list* head = malloc(sizeof(struct list));
head->data = malloc(sizeof(int));
*head->data = 1;

/* so far ok. */
head->next = malloc(sizeof(struct list));

int i = 0;
for (struct list* plist = head; plist != NULL; plist = plist->next)
{
    if (plist->data != NULL)
    {
        printf("data at element %d == %d\n", i, *(plist->data));
    }
    i++;
}
/* The first element (0) will print just fine.
 * Accessing data in the second element will,
 * or even accessing the list element itself
 * will likely result in a SEGFAULT.
 * Changing the malloc's to calloc() calls
 * will let this code run to completion.
 */

Edited 1 Year Ago by rubberman

This article has been dead for over six months. Start a new discussion instead.