Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Pointer arithmetic in Python

I'm trying to convert a simple C program into Python but as I don't know anything about C and a little about Python its just difficult for me..

I'm stuck at C pointers.

There is a function that takes an unsigned long int pointer and adds its values to some variables within a while-loop:

uint32_t somename(const uint32_t *z) {
    while(....) {
        a += z[0]
        b += z[1]
        c += z[2]
        z += 3
    }
}

Can someone please tell me how to accomplish the same thing in python? (The part that I didn't understand at all is " z += 3 ")

I'm aware that there aren't pointers in python. (at least not like C) But the problem is that I don't know what C pointers exactly do and therefor can't make this happen in python.

like image 541
eymen Avatar asked Dec 22 '22 15:12

eymen


2 Answers

A similar code snippet in Python might be:

def somename(z):
    i = 0
    while (....):
        a += z[i]
        b += z[i+1]
        c += z[i+2]
        i += 3

In C, z works sort of like an array index, except it starts at whatever the address of the start of the array is, rather than starting at 0. There is no analogous concept in Python, so you need to use a list index explicitly.

Whatever is inside (....) will need modification too. I'll leave that as an exercise for you, since it's unspecified in the question.

like image 151
Greg Hewgill Avatar answered Jan 06 '23 11:01

Greg Hewgill


What z += 3 means is basically advance the pointer 3 elements down. Say you have a pointer to an array in C called lst which contains [1, 2, 3, 4]. The pointer lst points to the first element such that *lst is equivalent to lst[0]. Furthermore, *(lst+1) is equivalent to lst[1].

like image 23
nevets1219 Avatar answered Jan 06 '23 13:01

nevets1219