【发布时间】:2017-05-23 13:48:22
【问题描述】:
背景:
我正在尝试创建一个程序,该程序采用用户名(假设输入是干净的),并打印出名称的首字母。
目标:
- 尝试使用 CS50 进行 C 编程
- 熟悉 malloc 和 realloc
代码:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
string prompt(void);
char *getInitials(string input);
char *appendArray(char *output,char c,int count);
//Tracks # of initials
int counter = 0;
int main(void){
string input = prompt();
char *output = getInitials(input);
for(int i = 0; i < counter ; i++){
printf("%c",toupper(output[i]));
}
}
string prompt(void){
string input;
do{
printf("Please enter your name: ");
input = get_string();
}while(input == NULL);
return input;
}
char *getInitials(string input){
bool initials = true;
char *output;
output = malloc(sizeof(char) * counter);
for(int i = 0, n = strlen(input); i < n ; i++){
//32 -> ASCII code for spacebar
//9 -> ASCII code for tab
if(input[i] == 32 || input[i] == 9 ){
//Next char after spaces/tab will be initial
initials = true;
}else{//Not space/tab
if(initials == true){
counter++;
output = appendArray(output,input[i],counter);
initials = false;
}
}
// eprintf("Input[i] is : %c\n",input[i]);
// eprintf("Counter is : %i\n",counter);
// eprintf("i is : %i\n",i);
// eprintf("n is : %i\n",n);
}
return output;
}
char *appendArray(char *output,char c,int count){
// allocate an array of some initial (fairly small) size;
// read into this array, keeping track of how many elements you've read;
// once the array is full, reallocate it, doubling the size and preserving (i.e. copying) the contents;
// repeat until done.
//pointer to memory
char *data = malloc(0);
//Increase array size by 1
data = realloc(output,sizeof(char) * count);
//append the latest initial
strcat(data,&c);
printf("Value of c is :%c\n",c);
printf("Value of &c is :%s\n",&c);
for(int i = 0; i< count ; i++){
printf("Output: %c\n",data[i]);
}
return data;
}
问题:
输出不是我所期望的,因为输出中出现了一个神秘的 P。
例如,当我输入巴拉克奥巴马这个名字时,我得到的不是结果:BO,而是结果 BP,无论我选择输入什么名字都会发生同样的情况,最后一个首字母始终是 P。
输出:
Please enter your name: Barack Obama
Value of c is :B
Value of &c is :BP
Output: B
Value of c is :O
Value of &c is :OP
Output: B
Output: P
BP
我做了什么:
我已经将问题追溯到 appendArray 函数,更具体地说是 &c(c 的地址)的值,尽管我不知道是什么导致了 P 出现,它意味着什么,它为什么出现以及我怎么能摆脱它。
无论我什么时候输入,P的值都会显示出来。
我们将不胜感激有关它发生的原因以及我能做些什么来解决它的见解。
谢谢!
【问题讨论】:
-
有一个cs50 stack exchange site,如果你有兴趣的话。
-
@pmg 我不知道。感谢您指出!
-
output = malloc(sizeof(char) * counter);-->output = malloc(++counter); *output = 0; -
strcat(data,&c); printf("Value of c is :%c\n",c); printf("Value of &c is :%s\n",&c);-->strncat(data, &c, 1); -
for(int i = 0; i < counter ; i++){-->for(int i = 0; output[i] ; i++){