C String es correcto en una función y descarga basura en la otra

Este es mi codigo

#include <stdio.h>

void abc(char *text);

int main(void)
{
    char text[20];
    abc(text);
    printf("text in main : %s\n",text);
    return 0;
}

void abc(char *text)
{
    text = "abc";
    printf("text in abc function : %s\n",text);
}

And this is output.

text in abc function : abc
text in main : ฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬฬ๑ป ๚

Mis preguntas son las siguientes:

  1. Why is the text variable in the main function and in the abc function is not the same?
  2. I try to change to use scanf en el objeto abc function and it works! there are the same. Why?
  3. How to modify the code to make it work. I means from question1 that make main function and in abc function are the same?

preguntado el 10 de mayo de 11 a las 13:05

2 Respuestas

When you call the function:

 abc(text);

una copia del puntero text is made, and this pointer is the one used in the function abc(). So that when you say:

text = "abc";

you are changing the copy, not the one back in main.

Also, you cannot in general assign strings in C - you have to use library functions like strcpy() instead. To make your code work, you need to change:

 text = "abc";

hasta:

 strcpy( text, "abc" );

contestado el 10 de mayo de 11 a las 17:05

A really easy mistake for newbies to make with pointers, they can take a little while to wrap your head around - Dan F

If I have an address of text in main function, can I modify in abc function (Pass by reference) ? - korrawit

@Atom The code I posted will modify the buffer in main - have you tried it? - user2100815

No puedes simplemente printf("text in main : %s\n",text); it has no meaning in C, you either can use a function like strcpy() that takes each char and organize them to be a Cordón ! or a regular for loop and run it all over the array and print organs without space.

int i;
for (i=0 ; i<strlength(text);i++)
{
    printf ("%d",text[i]);
}

contestado el 10 de mayo de 11 a las 17:05

I believe it's strlen() not strlength for C (strlength is C++ I believe). The %s format identifier most definitely will work with his example, and %d will show the ASCII representation of text[i], you want %c there. - Richard Holland

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.