0

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.

3
  • What you have here will print unexpected values but shouldn't segfault. That's probably being caused by code you haven't shown. Please update your question with a minimal reproducible example. Commented Apr 30, 2018 at 20:56
  • You might get a segfault if you tried to print that array using %s format, since it doesn't have a trailing null byte. Commented Apr 30, 2018 at 21:27
  • What compiler are you using? Commented Apr 30, 2018 at 21:39

1 Answer 1

5

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

for (i = 0; i < 5; i++) {
    printf("%c", *(array1 + i));
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.