Reputation: 21
I am trying to make a program that inserts 'abc' into a string. What is the problem with this code? I can not find a mistake.
// Elvis’s hip and happening ABC-printing code
#include <stdio.h>
#include <string.h>
#define NUM_ABC_LET 27
char makeABC(char abc[NUM_ABC_LET]);
int main(void)
{
char abcString[NUM_ABC_LET] = "";
makeABC(abcString);
puts(abcString);
return (0);
}
char makeABC(char abc[NUM_ABC_LET])
{
char letter = ' ';
for (letter = 'a'; letter <= 'z'; letter++)
{
strncat(abc, letter, NUM_ABC_LET);
}
return abc;
}
Upvotes: 2
Views: 91
Reputation: 1092
you are passing to strncat
a char instead of char* (a character instead of the address of it)
here is strncat prototype:
char *strncat(char *dest, const char *src, size_t n);
it copies n
chars from a string (char*) to another one
what strncat did with your code was trying to find what is at address 'a' (97) and sent you a segfault because the address 97 does not belong to your program so it crashed. instead you should tell him where is the variable (example 2) the most important is to understand how memory work in C
you did not need strncat for this purpose so here is a version without one:
char makeABC(char abc[NUM_ABC_LET])
{
int x;
x = 0;
while (x < NUM_ABC_LET)
{
abc[x] = x + 'a';
x += 1;
}
return abc;
}
and a version with it:
char makeABC(char abc[NUM_ABC_LET])
{
char letter = ' ';
for (letter = 'a'; letter <= 'z'; letter++)
{
strncat(abc + letter - 'a', &letter, 1);
}
return abc;
}
or you could just have done
char makeABC(char abc[NUM_ABC_LET])
{
strncat(abc, "abcdefghijklmnopqrstuvwxyz", NUM_ABC_LET);
return abc;
}
Upvotes: 0
Reputation: 17713
strncat(abc, letter, NUM_ABC_LET);
Problem is with your strncat
, the 2nd param needs to be a const string, but here you have it as a single char.
For your case, I think it'd be better to use snprintf
. So instead of strncat
, you can use this in your loop:
int pos = letter - 'a';
snprintf(abc + pos, NUM_ABC_LET - pos, "%c", letter);
Upvotes: 2