Kennedy Lajustra
Kennedy Lajustra

Reputation: 13

SIGSEGV, Segmentation fault. while printf() value of index of an array

I want to know how scanf and array works, so i create a code that print the value of each index of an array line-by-line.

#include<stdio.h>
int main(){
    char a[35];
    scanf("%30s", a);
    for(int i=0;i<30;i++){
        printf("index %d value :%s\n",i,a[i]);
    }
}

but I get an error while compiling the code. After I debug the code, i get "Program received signal SIGSEGV, Segmentation fault." I'm using Dev-C++

Upvotes: 0

Views: 367

Answers (2)

secondjohn
secondjohn

Reputation: 21

Agree with above answer. %s says dereference the arg and display the contents. a[i] is using an 8-bit valiue as a pointer.

Upvotes: 2

user000001
user000001

Reputation: 33387

When compiling with g++ I get this warning:

test.cc: In function ‘int main()’:
test.cc:6:45: warning: format ‘%s’ expects argument of type ‘char*’, but argument 3 has type ‘int’ [-Wformat=]
         printf("index %d value :%s\n",i,a[i]);
                                         ~~~~^

You probably want to change %s to %c, since each element of the array is a char:

printf("index %d value :%c\n",i,a[i]);

Upvotes: 2

Related Questions