0

I want to create a function in c, which creates every 8 increments (to be exact, when an integer holds the value 8) a paragraph/new line (and also prints an offset).

In this case, i've got an array

for (int i = 0; i < sizeof(myarray); i++){
printf(" %02hhX", myarray[i]);
}

Now i want to implement my function like this

int row = 0;
for (int i = 0; i < sizeof(myarray); i++){
printf(" %02hhX", myarray[i]);
check_newline(row);
}

The function 'check_newline' has this structure:

void check_newline(int row){
        row++;
        if(row==8){
        offset = offset + 8;
        row= 0;
        printf("\n%06X", offset);        
        }
}

Everytime, the integer 'row' reaches the value 8 a new offset will be printed and the value of 'row' will be reset to 0.

Now, i don't know how to implement the return; and with this code, my output looks like this

000008 E0 60 66 64 38 7D E0 60 66 64 38 7D 80000008 80 00 FF FF FF FF FF FF 000010 E0 60 66 64 38 7D E0 60 66 64 38 7D 80000010 80 00 FF FF FF FF FF FF

(totaly wrong)

When i 'put the function inside my code' (so basicaly don't use a function), everything is nice, because of the missing return statement.

for (int i = 0; i < sizeof(myarray); i++){
    printf(" %02hhX", myarray[i]);
    row++;
    if(row==8){
    offset = offset + 8;
    row= 0;
    printf("\n%06X", offset); 
}

000000 80 00 FF FF FF FF FF FF
000008 E0 60 66 64 38 7D E0 60

I have to use this kind of calculation often in my code, so a function will be more sleek.

  • 1
    function arguments are passed *by value*, you have a *local copy* of your `row` inside your function. In fact, this *has* to be a duplicate... (but I can't find a suitable one right now) –  Jun 20 '17 at 09:58
  • Please indent your code. – Jabberwocky Jun 20 '17 at 10:04
  • Possible duplicate of [Passing by reference in C](https://stackoverflow.com/questions/2229498/passing-by-reference-in-c) –  Jun 20 '17 at 10:07

1 Answers1

1

You are over complicating things. You don't need the extra variables as you can make use of i and the % (modulo operator) to work out when you're at the beginning or end of a row like this.

for (int i = 0; i < sizeof(myarray); i++) {
  if (i % 8==0) {
     printf("%06X",i);
  }
  printf(" %02hhX", myarray[i]);
  if (i % 8==7) {
     printf("\n");
  }
}
Chris Turner
  • 8,082
  • 1
  • 14
  • 18