Arash Arash - 2 months ago 16
C Question

loop executes only once with pointer assignment

I have a simple code to reverse a string:

char* reverse(char* s){
int i,j,len=strlen(s);
char* r;


for(i=len-1,j=0;i>=0;i--,j++){
printf("%d:%c\n",j,s[i]);
r[j]=s[i];
}


assume input string is "abc" , then the output "Without" the line
r[j]=s[i];
inside loop is :

0:c
1:b
2:a


if I include the
r[j]=s[i]
assignment, output stops at it!

0:c


Why the assignment stops the loop here?

Answer

First of all, you are writing to uninitialized pointer: char* r is declared, but never allocated. Allocate memory dynamically or on the stack, then write into it. For example:

char* r = malloc(len + 1);

Right now your code is most likely crashing when you are trying to access uninitialized memory.

Comments