0

I'm trying to return an array from a function and to do that a have a pointer in the function but when i try to return the array it returns only the first element! :S

This is my code:

int* getDate() {
    time_t t = time(NULL);
    struct tm tm = *localtime(&t);

    int i;
    static int date[7];//i save in each position the year, month, day, h, m and s

    date[0] = tm.tm_year + 1900;
    date[1] = tm.tm_mon + 1;
    date[2] = tm.tm_mday;
    date[3] = tm.tm_hour;
    date[4] = tm.tm_min;
    date[5] = tm.tm_sec;

    return date;    
}

int main(){
    int *p;
    int i;
    p = getDate();

    for (i = 0; i<6; i++){
        printf("%d/", *p);
    }

    return 0;
}

Desired output: 2014/12/24/3/44/12 (year/month/day/hour/minute/seconds)

Current output: 2014/2014/2014/2014/2014/2014

1
  • 1
    Perhaps you meant to print p[i] or *p++? As written, you print the first element of p six times. Commented Dec 24, 2014 at 2:53

3 Answers 3

2

make this change.

for (i = 0; i<6; i++){
    printf("%d/", p[i]);

You have retuned a pointer to the array, pointers can in many ways be used like arrays.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you! so stupid mistake. i thought that being a pointer function must had the pointer :(
1

use *(p+i) in the for loop inside main

Comments

0

The problem is not with the return value it is with your print statement. An array is exactly the same thing in C as a pointer: it's really just a pointer to the first element. You can then just add your index to the pointer before dereferencing to get the correct array item.

Change your print statement to printf("%d/", *(p + i));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.