1

I tried making code counting elements in array, and it works.
The problem is gcc prints different output with a for-statement in main() and from the function call countreturn(size_t sz, int *arr).

Here is output and code right below.. output:

----------

1 1 1 1 1

1 1 1 1 32766

5

0


The for-statement prints 1, instead 32766, but when using function it prints 32766.

#include<stdio.h>
int countreturn(size_t sz, int *arr){   
    int i=0, count = 0;
    while(arr[i]!='\0'&&i<sz){
        ++i;
        ++count;
        printf("%d ",arr[i]);
    }
    printf("\n");
    return count;
 }

int main(){
 int store[5] = {[0 ... 4] = 1 };
 printf("-----------------\n");
 for(int i = 0; i <5; ++i){
    printf("%d ", store[i]);
 }
 printf("\n");
 printf("-----------------\n");

 int store2[500] = {'\0',};

 printf("%d\n", countreturn(sizeof(store)/sizeof(int),store));
 printf("%d\n", countreturn(sizeof(store2)/sizeof(int),store2));
return 0;
}
2
  • by the way, gcc version is 4.2.1 and I use mac os x Commented Jul 8, 2018 at 17:11
  • 1
    If the array dimension is 5 and it is holding 5 elements, where is the '/0' end marker? Commented Jul 8, 2018 at 17:15

2 Answers 2

1

the problem is you are incrementing value of i first and then printing value stored at ith index, that's why your code is printing garbage value.

#include<stdio.h>
int countreturn(size_t sz, int *arr){
int i=0, count = 0;
while(arr[i]!='\0'&&i<sz){
    printf("%d ",arr[i]);              //print first then
    ++i;                               // increment value if i
    ++count;
}
    printf("\n");
    return count;
}

int main(){
int store[5] = {[0 ... 4] = 1 };
printf("-----------------\n");
for(int i = 0; i <5; ++i){
printf("%d ", store[i]);
 }
 printf("\n");
 printf("-----------------\n");

 int store2[500] = {'\0',};

 printf("%d\n", countreturn(sizeof(store)/sizeof(int),store));
 printf("%d\n", countreturn(sizeof(store2)/sizeof(int),store2));
 return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Move your increment to print array elements 0-4,
instead of elements 1-5, which means accessing beyond the array size and gets you undefined behaviour and thereby any weird value.

while(arr[i]!='\0'&&i<sz){
    ++count;
    printf("%d ",arr[i]);
    ++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.