如果我不在函数中使用 printf 或动态分配,我将无法调用函数。为什么?
I can't call function if i don't use printf or dynamic allocation in function. why?
我用了Repl compiler.
First issue : If I don't use "printf" function, I can't call fucntion.
#include <stdio.h>
#include <string.h>
char *m_strncpy(char *str1, int count) {
int i;
char *new_str;
for (i = 0; i < count; i++) {
new_str[i] = str1[i];
}
return new_str;
}
int main(void)
{
char str[80];
char *sp, e;
int count;
printf("Enter a string : ");
fgets(str, sizeof(str) - 1, stdin);
printf("The number of character : ");
scanf("%d", &count);
//printf("Input complete\n");
sp = m_strncpy(str, count);
printf("Cut string is %s\n", sp);
return 0;
}
如果我不使用 printf("Input complete\n");
则不会调用 m_strncpy
函数。
Second issue : If I don't use dynamic allocation in m_strncpy
function, I can't call function.
Visual Studio 2017 不允许取消初始化。但是Repl编译器允许。
所以当我不初始化char *new_str
时,是无法调用的。为什么??
您的原始代码表现出未定义的行为:
char *m_strncpy(char *str1, int count) {
int i;
char *new_str; // new_str is not initialized, it doesn't
// point anywhere
for (i = 0; i < count; i++) {
new_str[i] = str1[i]; // dereferencing an uninitialized pointer is undefined
// behaviour, anything can happen.
}
return new_str;
}
你可能想要这个:
char *m_strncpy(char *str1, int count) {
int i;
char *new_str = malloc(count + 1); // +1 for the NUL terminator
if (new_str != NULL)
{
for (i = 0; i < count; i++) { // copy count first chars
new_str[i] = str1[i];
}
new_str[i] = 0; // NUL terminate the string
}
return new_str;
}
我用了Repl compiler.
First issue : If I don't use "printf" function, I can't call fucntion.
#include <stdio.h>
#include <string.h>
char *m_strncpy(char *str1, int count) {
int i;
char *new_str;
for (i = 0; i < count; i++) {
new_str[i] = str1[i];
}
return new_str;
}
int main(void)
{
char str[80];
char *sp, e;
int count;
printf("Enter a string : ");
fgets(str, sizeof(str) - 1, stdin);
printf("The number of character : ");
scanf("%d", &count);
//printf("Input complete\n");
sp = m_strncpy(str, count);
printf("Cut string is %s\n", sp);
return 0;
}
如果我不使用 printf("Input complete\n");
则不会调用 m_strncpy
函数。
Second issue : If I don't use dynamic allocation in
m_strncpy
function, I can't call function.
Visual Studio 2017 不允许取消初始化。但是Repl编译器允许。
所以当我不初始化char *new_str
时,是无法调用的。为什么??
您的原始代码表现出未定义的行为:
char *m_strncpy(char *str1, int count) {
int i;
char *new_str; // new_str is not initialized, it doesn't
// point anywhere
for (i = 0; i < count; i++) {
new_str[i] = str1[i]; // dereferencing an uninitialized pointer is undefined
// behaviour, anything can happen.
}
return new_str;
}
你可能想要这个:
char *m_strncpy(char *str1, int count) {
int i;
char *new_str = malloc(count + 1); // +1 for the NUL terminator
if (new_str != NULL)
{
for (i = 0; i < count; i++) { // copy count first chars
new_str[i] = str1[i];
}
new_str[i] = 0; // NUL terminate the string
}
return new_str;
}