How to initialize an array using pointers? [closed]

-7

I need to initialize an array with 0 using pointer to address its elements

    
asked by anonymous 12.02.2014 / 23:27

3 answers

5

See if this is what you want:

int main()
{
    int matriz[5][5], i, *ponteiro;
    ponteiro = matriz[0];
    for (i = 0; i < 25; i++)
    {
        *ponteiro = 0;
        ponteiro++;
    }

    return 0;
}

It's pretty much the same thing that was answered in your question

13.02.2014 / 00:20
4
#include <string.h>

/* ... */

int matrix[3][4];
memset(matrix, 0, 3 * 4 * sizeof(int));

The memset function receives a pointer, a value, and a quantity. It will fill that amount of bytes from the pointer with that value.

Because the size is in bytes, the quantity must be multiplied by the size of the array type.

Edit: As suggested in the comment for this answer, you can do the following as well:

memset(matrix, 0, sizeof(matrix));

This is possible because the compiler knows the full size of the array, since its dimensions are defined in the variable. But if you instead had a pointer to the array, that would not be possible:

int *ptr = &matrix[0][0];
memset(ptr, 0, sizeof(ptr));         /* ERRADO:  vai zerar apenas o primeiro elemento */
memset(ptr, 0, 3 * 4 * sizeof(int)); /* CORRETO: vai zerar toda a matriz */
    
13.02.2014 / 08:44
4

Four ways to zero a matrix come to mind, among them the easiest would be this:

int matriz[5][5] = {0};

The normal, basic level, would be this:

int matriz[5][5], i, j;
for(i=0; i<5; i++)
{
    for(j=0; j<5; j++)
    {
        matriz[i][j]=0;
    }
}

An intermediary, I believe it is the one you want, would be working with pointers. Since the allocation is sequential, the next or previous values will always be in the next house, going from the beginning to the end of matriz . I only see use for something of the type in an auxiliary function, because this way it is completely a waste of time, there is no need.

int matriz[5][5], i, j, *ptr=matriz;
for (i=0; i<25; i++, ptr++)
{
    *ptr=0;
}

And it has the advanced method, with memset() , here you move directly with memory, the first argument is the vector, the second is the value to be setado and the third is the amount of values of the vector to be setado in bytes. You first need to know what type of data you are working with, its size in bytes, you use the sizeof() function that receives the data and returns the number of bytes allocated to that data. So to clear matriz you could do just that:

memset(matriz, 0, sizeof(matriz));
    
15.02.2014 / 03:07