Search code examples
carraysfunctionpointersint

Using a pointer to an array passed as a parameter of a function


I'm a beginner in C and I'm trying to use a pointer in my function.

I'm trying to fill an array of int by using a pointer passed as an argument of the function, but I don't know how to do it properly.

How can I do this correctly?

Function

int validate_ip(char *ip, int *ptid) { /*function where I want to use it*/ }

ip is a char array that contains an ipv4 address.

Main

int main() {

    int ipv4[4];
    int *ptid = ipv4;

    //rest of my programm
} 

Solution

  • You can pass the ipv4 int array to a pointer to int argument, what will happen is that it will decay to a pointer to its first element, to work properly with the array inside the function you should also pass the size of the array.

    For example:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int validate_ip(char *ip, int *ptid, size_t size) {
    
        const char delim[] = ".";
        char *token;
        size_t i = 0;
    
        //tokenize the ip and convert it to int
        //this is for sample purposes, octet validation should be performed
        token = strtok(ip, delim);
        while (token != NULL && i < size) {
            ptid[i++] = atoi(token);
            token = strtok(NULL, delim);
        }
        return 1;
    }
    
    int main()
    {
        char ip[] = {"192.168.0.3"}; //sample ip
        int ipv4[4];
    
        if(validate_ip(ip, ipv4, 4)){
            for (int i = 0; i < 4; i++)
            { 
                printf("%d ", ipv4[i]);
            }
        }
    }
    

    This will need the validations to check if the octets in the ip char array are correct, but I believe you already done that.

    One last note regarding my sample code, strtok will make changes in the ip char array, if you want to prevent this, make a copy of it and pass it to the function instead of the original ip.