Home > Back-end >  C char array pointer confusion
C char array pointer confusion

Time:09-25

I have written following c code

#include <stdio.h>
#include <stdlib.h>

void func1(char *arr){
    printf("%d\n",arr[0]);
    printf("%d\n",arr[1]);
    return;
}

int main () {
    char a[6] = "hello";
    printf("%p\n",a);
    printf("%p\n",&a);
    func1(a);
    return 0;
}

when I executed this code I am getting following output

0x7fff5a7323e2
0x7fff5a7323e2
104
101

Following are my doubts:

  1. why value of arr[1] is less than arr[0], and what are these values
  2. Suppose we are given 0 to 1073741823 is the valid memory range and we have to check if array passed to func1 is in valid range then how to check that.

CodePudding user response:

What you need is to understand formatted string for printf. printf("%d\n",arr[0]); expected to print an integer to the output. But in C, character can be treated as integer based on its coded value in memory. For example, 104 represents "h" according to ASCII coding. And 101 represents "e". The memory allocated for your array is managed by system, you not suppose to check if they are in valid range or not. But you can always treat them as integer and use simple compare operators.

CodePudding user response:

For the second part, you can convert hexadecimal address to decimal and compare it with the provided range

  • Related