简体   繁体   中英

C char array pointer confusion

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 is value of arr[1] 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.

1. Why is value of arr[1] less than arr[0] , and what are these values?

printf("%d\n",arr[0]) and printf("%d\n",arr[1]) will print the decimal values of the characters in those positions, since your character encoding is ASCII the decimal value of e ( arr[1] ) is 101 and the decimal value h ( arr[0] ) is 104, as you can check in the linked table.


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.

In this case, since it's a string, you know it will have a sentinel null byte at the end of the array, so you can use:

// initially arr will be pointing to the first element of the array
while(*arr != '\0'){ // will evaluate to false when the string ends
     
    //do stuff...
    arr++;

}

There are other ways of doing it, for example, pass the size of the array as second argument:

void func1(char *arr, int size){...}

and the call:

func1(a, sizeof a / sizeof *a);

This is more useful when your array is not a null terminated array, otherwise you can always use sentinels to signal the end of your arrays, the downside is that in most cases you'll need to add them yourself.


Note that the behavior of printf("%p\n", a) is undefined, you should have printf("%p\n", (void*)a) .

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM