z.rubi
z.rubi

Reputation: 327

Pass a pointer of an array to a function to use in printf` in C

I am having trouble with a segmentation fault and it seems to be coming from me trying to use printf() to dereference a single array value instead of using a pointer to the memory location that I want to print.

If I define an array in one function and want to pass that array to be referenced char by char in a loop containing printf(), how should I pass and reference the array?

void arrayFunc(){

  char array [5];
  array[0] = 'a';
  array[1] = 'b';
  array[2] = 'c';
  array[3] = 'd';
  array[4] = 'e';

  printArray(array);
}

void printArray(char* array1){
  int i;
  for(i = 0; i < 5; i++){
        printf("%c", array1 + i);
  }
}

Doesn't seem to get the job done.

Upvotes: 0

Views: 180

Answers (1)

Stephen Docy
Stephen Docy

Reputation: 4788

You need to dereference the pointer when you try to print out the char

for (i = 0; i < 5; i++) {
    printf("%c", *(array1 + i));
}

Upvotes: 5

Related Questions