gpt4 book ai didi

c - printf语句错误

转载 作者:行者123 更新时间:2023-11-30 20:12:26 25 4
gpt4 key购买 nike

我的最后一个 printf 语句没有打印我不确定出了什么问题,因为我使用 getchar 来读取标准输入,我还必须使用 %s 来解决这个问题。我试图让最后一个 printf 语句打印来自标准输入的确切输入。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define INITIAL_BUFFER_SIZE 16

// Input: pointer to the the old_Buffer i.e. *buffer and the pointer to the old_Buffer size i.e. *buffer_size
// Output: pointer to the new_Buffer i.e. *temp
// Summary: Function to increase the buffer size to double whenever the old_Buffer reaches the max possible size
char* IncreaseBuffer(char *buffer,int *buffer_size){

// Creating a new buffer of double the size
int temp_sz = *buffer_size;
temp_sz = 2*temp_sz;
char *temp;
temp = realloc(buffer, temp_sz);

// If the allocation is not successful, then exit the program and print the error
if (!temp) {
printf("Error: Unable to Realloc\n");
exit(EXIT_FAILURE);
}

// Update the buffer size as per the new buffer and return the new buffer instead of the old buffer
*buffer_size = temp_sz;
return temp;
}

int main(void){
// INITIAL BUFFER
char *myString;
myString = malloc(INITIAL_BUFFER_SIZE);
int curr_size = INITIAL_BUFFER_SIZE;

// TEMPORARY CHARACTER TO STORE THE READ CHARACTER
char ch;
printf("Enter a string: ");

// Number of buffer increases
int buff_inc = 0;

// Length of the string
int len = 0;

while((ch=getchar())!=EOF){
if(ch == '\n'){
// If character read is a new line, then we break and assume that we have got our string to print by now
break;
}else{
if(len >= curr_size - 1){
// If length of the string is greater than the buffer size, then we increase the buffer size
// Also increment the number of buffer increases
myString = IncreaseBuffer(myString, &curr_size);
buff_inc++;
}
// Append the read character to the end of the buffer
myString[len++] = ch;
}
}

printf("String size: %d\n", len);
printf("Buffer increases: %d\n", buff_inc);
printf("You entered: %s\n",myString);

return 0;
}

最佳答案

不得在调用realloc后释放旧缓冲区。那很不好。它已经调整了大小并处理了内存分配。它甚至可能在重新分配后保留相同的地址。

只需删除以下行:

// Free the old buffer
free(buffer);
buffer = NULL;

并且,已经在注释中指出,您忘记终止字符串。在循环之后执行此操作:

myString[len] = '\0';

关于c - printf语句错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35423746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com