LearningCODE
LearningCODE

Reputation: 165

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.

Upvotes: 1

Views: 389

Answers (2)

Mohamed Abd El Raouf
Mohamed Abd El Raouf

Reputation: 332

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.

Upvotes: 1

Darwin57721
Darwin57721

Reputation: 197

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

Upvotes: 2

Related Questions