0

Possible Duplicate:
Is array name a pointer in C?
Array Type - Rules for assignment/use as function parameter

This is the code that i wrote for an exercise in K&R C. The task is pretty simple, to replace '\t' with \ and t and not the tab character

the following is the code

char* escape(char s[], char t[]){
 int i = 0, j = 0;
 for(i = 0; t[i] != '\0'; i++){
   switch(t[i]){
     case '\t':{
        s[j++] = '\\';
        s[j++] = 't';
        break;
     }
     default:{
        s[j++] = t[i];
        break;
     }
   }
  }
 s[j] = t[i];
 return s;

 }


 int main(){        
    char t[10] = "what \t is";
    char s[50];
    s = escape(s,t);
    printf("%s",s);
    return 0;
 }

It returns an error saying inappropriate type assignment betweenn char[50] and char* but isn't the name of the array supposed to be the pointer to the first element?

Community
  • 1
  • 1
sukunrt
  • 1,523
  • 10
  • 20

3 Answers3

2

In C arrays aren't writable lvalues. You can't assign to them. In your code you don't actually need to return anything from the function since it changes s in place. But if you really want to:

char *s = malloc(...);
s = escape(s, t);

This means you will later have to free it etc. In short, don't return anything from the function and it's going to be ok.

but isn't the name of the array supposed to be the pointer to the first element

That's an over-simplification. Thing is arrays typically decay into pointers to the first element in certain contexts.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
0

You can assign an array to a pointer but not viceversa.

Luis
  • 1,294
  • 7
  • 9
0

It works the other way around: you can pass an array where a pointer is expected. But that doesnt mean you can assign a pointer to an array name. Think about it, when you say

char s[50];

the compiler just reserves space for 50 characters and remembers that s is a pointer to those 50 characters. It is, so to speak, a constant. You can change the characters in the array, but not where the array is.

Ingo
  • 36,037
  • 5
  • 53
  • 100