简体   繁体   中英

Passing an int pointer into a function to print that array in C

This is my first post so bear with me. I am getting back into writing in C after being out of school for a while. I am trying to pass an array of integers into a function that will print the entire array out on the same line (as a part of a larger effort). My dumbed down code follows:

// main.c
#include <stdio.h>

int main(void) {

    int arr[] = {3,4,5,6,7};
    int *ptr = arr;
    int l = 5;

    printarr(arr,l);
    return 0;
}

And

// function printarr
#include <stdio.h>

void printarr(char *ptr, int l) {

    int k = 0;
    for (k = 0; k < l; ++k) {
        printf("%d", ptr[k]);
    }
}

After compiling and running main.c, the output I get is:

30004

I feel like I have been beating my head against a wall trying to figure out a simple problem. When I iterate and print the array in main I get the output I would expect ('34567') but when I try to do it through the function it comes out sad. I suspect I am misusing the pointer but yeah I'm not sure.

Help is appreciated.

Thanks.

edit: Upon glancing at the first two comments, I am entirely ashamed of myself. Thank you folks. Wow, just wow.

You should change your function to

void printarr(int *ptr, int l)

as you're passing an int * to it. As pointed by @Malife, you should enable the compiler warnings with -Wall , so you get a proper message. Optionally make all warnings into errors with -Werror .

char and int have different sizes, int being much bigger. 4 times bigger as you can see from your output. You're iterating the memory where your int numbers are allocated in a partial manner when looking at the values as char .

printarr should be expecting an int array, not char array, so should be

 void printarr(int *ptr, int l)

In main, int *ptr = arr; is not used or needed.

You probally also want to put a space or new line between each value of the array you are printing out:

void printarr(char *ptr, int l) {

    int k = 0;
    for (k = 0; k < l; ++k) {
        printf("%d\n", ptr[k]);
    }
 }

I think the problem is that you pass a char pointer in "printarr". In fact when you pass "ptr" you have this situation: 00000011 00000000 00000000 00000000 00000100 .... A char has 8 bit, an int 32 bit, and the Ram is often Little Endian for the bytes order. Then you call a printf passing an int, and the byte is extended to 32 bits so you print: 3 0 0 0 4. In the main "ptr" is an int, so you print the int, in this case 3 4 5 6 7. You must change char *ptr -> int *ptr in "printarr"

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