c语言数组打印字符串,C语言打印循环中的数组字符串

OK,我会建议你做一些更有效的,并且是使用双指针。通过这样做,您可以解决2D阵列版本中存在的一些问题。

第一个问题是,如果用户想要插入超过999个糖果,你会怎么做。你的数组不能容纳它们。

其次,如果用户输入大于100个字符的名称,你会怎么做。再一次,你的二维数组不能容纳它。而且,尽管用户可能输入大于100个字符的名称,但大多数用户的输入会比这个少得多,现在对于每个字符串,当您可能只需要大约50个时,就会分配100个位置。

因此,让我们来处理这些问题。 我可能会做这样的事情:

#include

#include // for strcpy(), strlen()

#include // for malloc()

int main(void) {

char **sweet_names; // make a double pointer(or you might see that as array of pointers

char reader[300]; // this variable will help us read every name into the sweet_names

int sweet_number;

int i, j;

// Your code here to get the number of sweet_names

/*Prompts the user to enter the number of sweets and saves it to sweet_number*/

printf("Please enter the number of sweets:\n");

scanf("%d", &sweet_number);

// Now that you know the sweet_number, allocate as much memory as you need.

// And that can be more than 999 sweet names

sweet_names = (char **) malloc(sweet_number * sizeof(char *));

// i.e. make a character pointer to sweet_number character pointers.

// Again, some of your code here

for (i = 0; sweet_number > i; i++) {

printf("What is the name of the sweet?\n");

scanf("%s", reader); // read into the reader

sweet_names[i] = (char *) malloc(strlen(reader) + 1); // allocate as much memory as you need for the current string, the one just read into reader

strcpy(sweet_names[i], reader); // copy contents of reader to sweet_names[i]

}

// Again, your code to print the names

for (j = 0; sweet_number > j; j++){

printf("%s\n", sweet_names[j]);

free(sweet_names[j]); // free every string you allocated, it is good practice

}

// Finally, free the sweet_names pointers. Generally, when you allocate

// dynamically, which is what we do with malloc(), it is a good practice

// to free what you allocate becuase otherwise stays in memory and then

// memory leaks are created. There is a lot to say about C and memory

// but anyway, remember to free

free(sweet_names);

return 0;

}

最后,现在程序再次有限制只读名最多,因为reader 300个字符,但这个东西,你也可以处理,而这是为读者分配一个疯狂的内存量,如1000000 个字符,然后释放它。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值