我正在制作一个连接用户给出的两个字符串的程序。一切都很好,但我不知道为什么程序显示最终结果的sizeof是 8 位长。不管字符串有多长,它总是显示 8。我猜,它是char的大小,但我想知道它为什么会这样。这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* concatenate(char *fir, char *sec)
{
int firLen = strlen(fir);
int secLen = strlen(sec);
int len = firLen + secLen + 1;
int i = 0,c=0;
int *wsk = &i;
char *result = (char *)malloc(len*sizeof(char));
while (fir[i]!='\0')
{
result[i]=fir[i];
(*wsk)++;
}
while (sec[c]!='\0')
{
result[i]=sec[c];
(*wsk)++;
c++;
}
result[len-1] = '\0';
return result;
}
int main(int argc, char **argv)
{
char *first, *second, *output;
int size1, size2;
printf("How long will your first string be: ");
scanf("%d", &size1);
first = (char *) malloc ((1+size1)*sizeof(char));
if (!first)
{
puts("\nError. Can't allocate memory!");
abort();
}
printf("How long will your second string be: ");
scanf("%d", &size2);
second = (char *) malloc ((size2+1)*sizeof(char));
if (!second)
{
puts("\nError. Can't allocate memory!");
abort();
}
printf("\nPlease, type in the first string: ");
scanf("%s",first);
printf("\nPlease, type in the second string: ");
scanf("%s",second);
output = (char *)malloc((size1+size2+1)*sizeof(char));
output = concatenate(first, second);
printf("\nConcatenation of the strings: %s", output);
printf("\n%d", sizeof(output));
free(first);
free(second);
free(output);
getchar();
return 0;
}