C语言 在 C 中使用指针扫描字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13261169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:20:07  来源:igfitidea点击:

Scanning in a string using pointers in C

cstringpointersscanf

提问by kyle

Possible Duplicate:
Dynamic String Input - using scanf(“%as”)
strcmp with pointers not working in C

可能的重复:
动态字符串输入 - 使用 scanf(“%as”)
strcmp 和指针在 C 中不起作用

Is the following considered good code? Shouldn't I have used malloc somewhere? I was able to compile this and it worked, but I feel like it shouldn't have.

以下被认为是好的代码吗?我不应该在某处使用 malloc 吗?我能够编译它并且它起作用了,但我觉得它不应该有。

#include <stdio.h>

int main (void) {

    char *name;

    printf("Whats your name? ");
    scanf("%s", &name);
    printf("\nyour name is %s", &name);

    return 0;
}

What happens if I want to modify name? How would I go about doing so?

如果我想修改名称会怎样?我该怎么做?

Edit: I am really just looking for the most efficient and correct way to do this using pointers. I am assuming malloc is necessary.

编辑:我真的只是在寻找使用指针执行此操作的最有效和正确的方法。我假设 malloc 是必要的。

回答by MRAB

nameis a pointer, and &namereturns the address of the variable name, so the scanfis putting the name you enter into the pointer itself.

name是一个指针,并&name返回变量的地址name,因此scanf将您输入的名称放入指针本身。

For example, if you enter ABCthen the pointer will be 0x00434241 (if the CPU is little-endian) or 0x41434200 (if the CPU is big-endian), where 0x41 is the character code for 'A', 0x42 is the character code for 'B', etc.

例如,如果您输入,ABC则指针将是 0x00434241(如果 CPU 是小端)或 0x41434200(如果 CPU 是大端),其中 0x41 是“A”的字符代码,0x42 是“A”的字符代码'B' 等。

You should allocate memory into which the entered name can be stored and then pass a pointer to it to scanf.

您应该分配可以存储输入名称的内存,然后将指向它的指针传递给scanf.

Here's an example allocating on the stack:

这是在堆栈上分配的示例:

#include <stdio.h>

#define MAX_NAME_LENGTH 256

int main (void) {

    char name[MAX_NAME_LENGTH];

    printf("Whats your name? ");
    scanf("%s", name);
    printf("\nyour name is %s", name);

    return 0;
}

回答by Alberto Bonsanto

Alternatively You can use gets too, to avoid the Standard Input buffer in cases that you have more than 2 sequential inputs.

或者,您也可以使用 get,以避免在您有 2 个以上连续输入的情况下使用标准输入缓冲区。

#include <stdio.h>

#define LENGTH 256

int main (void) {

   char name[LENGTH];

   printf( "Whats your name? " );
   fgets( name, sizeof( name ), stdin );
   printf( "\nYour name is %s", name );

   return 0;
}