0
   #include <stdio.h>
void swapchars(int Q,char* L){
     char *ptr;
        for(int i=0;i<Q-1;i+=2){
        *ptr= *(L+i);
        *(L+i)= *(L+i+1);
        *(L+i+1)= *ptr;
        }
}
int main() {
    // Write C code here
    int N;
    scanf("%d",&N);
        char str[N+1];
        scanf("%s",str);
       swapchars(N,str);
        printf("%s",str);
    return 0;
}

I don’t know what is wrong with this code it keeps generating segfault although when I used the same loop directly in the main function without an external function the code was working properly

1 Answers1

1

You haven't initialized ptr to anything, so dereferencing it is undefined - you are writing to a random place in memory.

Think about whether you really need a pointer to store the intermediate value.

MadMan
  • 126
  • 5