dante
dante

Reputation: 1111

different print output of elements in integer array

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;
}

Upvotes: 1

Views: 205

Answers (2)

Vikas Gautam
Vikas Gautam

Reputation: 441

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;
}

Upvotes: 1

Yunnosch
Yunnosch

Reputation: 26703

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;
}

Upvotes: 1

Related Questions