简体   繁体   中英

How to enter char* in C?

Its a simple input that I want to make for char*. Why is this not working? It throws me an exception that I can't resolve..

#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"

char* GetCharSeq()
{
    char *s = (char*)malloc(100);

    scanf_s("%s", s);

    return s;
}

int main()
{
    char* charseq;

    charseq = GetCharSeq();

    return 0;
}

You have undefined behavior in your code. You have it because you provide to few arguments to the scanf_s function.

For every string argument, you need to provide not only the destination string but also the size of the string. So change your call to

scanf_s("%s", s, 100);

modify your code

char* GetCharSeq()
{
    char *s = (char*)malloc(100);

    gets(s);

    return s;
}

This will 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