简体   繁体   中英

c pass a string to function then return a string

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char *abc = "abc";
    char *new_str;
    new_str = getStr(&abc);
    printf("%s", abc);
}

char *getStr(char *str)
{
    printf(str);
    return str;
}

What's wrong with the code above?

A bunch of small things:

  1. You're passing &abc to getStr() . &abc is a pointer to the variable that is holding your string. Its type a pointer to a pointer, and that's incompatible with the char *str argument of getStr().

  2. Your getStr() is defined after it is used. You either need to move its definition to before main() or add a prototype before main() .

  3. The type of a string literal like "abc" is const char * . You're defining a variable of type char * , which is dubious (since it would allow you to modify a string literal, which is not allowed).

here is a working version:

#include <stdio.h>
#include <stdlib.h>

char *getStr(char *str);

int main(void)
{
    char *abc = "abc";
    char *new_str;
    new_str = getStr(abc);
 //printf("%s", *abc); don't really need this
}

char *getStr(char *str) {
 printf("%s", str);
 return str;
}

Here's a list of problems with the old one:

  1. No prototype for your function getStr.
  2. You can't do printf(str) you need a "%s" as an additional param.
  3. You need to change: new_str = getStr(&abc) to new_str = getStr(abc)

AC string is a pointer to a character that begins a sequence of characters that end with a null byte. The variable abc perfectly fits this definition.

Also, abc is of type pointer to character. You are passing the address of abc, ie getStr will be receiving the address of a pointer to a character--so getStr's only argument should be of type pointer to pointer to character. The types do not match up.

EDIT: Also, getStr is called before it's declared. Your compiler may allow this, but it's bad practice for many reasons. You should declare it or define it before it is used. If you are using gcc as your compiler, always use

gcc -ansi -Wall -pedantic

Those three flags will conform to ANSI standards, and it would either yell at you for the above issues or not compile.

Your getStr function takes a char *, but that's not what you're passing it - you're passing the address of the pointer, instead of passing it the actual pointer.

Change:

new_str = getStr(&abc);

to:

new_str = getStr(abc);

and I think it'll work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM