简体   繁体   中英

C - Having trouble with sprintf and printing strings

#include <stdio.h>
#include <string.h>
int main() {
    char buf[100];

char *word1 = 'Holy';

char *word2 = 'Moly';
sprintf(buf,"%s %s", word1, word2);
printf("%s\n", buf);

}

Hello I'm trying to use sprintf, however I can't seem to get this program to work, am I doing something wrong? It compiles, but when I run it it gives me segmentation fault ( core dumped) or it crashes.

You are missing the double quotes for the char*

#include <stdio.h>
#include <string.h>

int main() {
    char buf[100];
    char *word1 = "Holy";
    char *word2 = "Moly";
    sprintf(buf,"%s %s", word1, word2);
    printf("%s",buf);
}

Edit: And don't forget to use gcc -Wall to show ALL the warnings to spot more easily these mistakes! :D

Try fixing these lines :

char *word1 = 'Holy'; 
char *word2 = 'Moly';

to:

char *word1 = "Holy";
char *word2 = "Moly";

That is because single quotes are only used with a single character not a string value. Always pay attention to compiler warnings especially when you are dealing with pointers. If the compiler warnings was not enabled try enabling them as Darwin57721 explained.

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