mic*_*ael 1 c concatenation sizeof
我正在制作一个程序,用于连接用户给出的两个字符串.一切都很好,但我不知道为什么程序显示最终结果的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;
}
Run Code Online (Sandbox Code Playgroud)
不要sizeof用来确定字符串长度,使用该strlen函数,就像在程序的其他部分一样.
printf("\nConcatenation of the strings: %s", output);
printf("\n%d", strlen(output));
Run Code Online (Sandbox Code Playgroud)
使用sizeof确定的大小的数据类型,如char,一个struct,阵列等
你提到要使用sizeof来检查,如果一切正常内存分配,但你不能使用sizeof与分配的内存缓冲区这样malloc:你只能依靠的返回值malloc-你不检查 - 知道您的分配是否成功.
您可以使用它sizeof来确定数组的大小:
char myStr[13];
printf("%d\n", sizeof(myStr));
Run Code Online (Sandbox Code Playgroud)
但这仅适用于数组,而不适用于使用的缓冲区malloc.
此行也会因为您在下一行中覆盖指针而产生内存泄漏:
output = (char *)malloc((size1+size2+1)*sizeof(char));
Run Code Online (Sandbox Code Playgroud)