2

I am just learning some pointers stuff in C and I happened to learn that using the * one can dereference the pointer. So I wrote the following code to check for that.

#include<stdio.h>
#include<string.h>

char *findChar(char *s, char c){
  while(*s!=c){
     s++;
  }
  return s;
}

int main(){
  char myChar='a';
  const char myString[]="Hello abhishek";
  char *location;
  location = findChar(myString,myChar);
  puts(location);
  char temp = *location;
  printf(temp);
}

I assume that temp should get the value pointed by the character pointer location, But this program is giving me a segmentation fault. Please clearify what I am doing wrong?

madth3
  • 7,275
  • 12
  • 50
  • 74
Abhishek
  • 2,543
  • 4
  • 34
  • 46
  • If your string doesn't have an `a` in it, your findchar routine goes out of bounds. Also, consider using a debugger to find faults like the one mentioned by aix. – Adam Davis Jan 19 '12 at 16:18

3 Answers3

7

The following is incorrect:

 char temp = *location;
 printf(temp);

If you want to print out the char, use the following:

 char temp = *location;
 printf("%c\n", temp);

The first argument to printf() should be the format string.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

The first argument of printf should be char* (for the format), not char.

Try printf("%c\n",temp);

By the way, to see the index of myChar in the array, you may want to print location-myString

asaelr
  • 5,438
  • 1
  • 16
  • 22
0

The printf causes the segmentation fault, as printf expects a char pointer for temp and you pass a single char to it.

boto
  • 455
  • 2
  • 13