在scanf中使用整数变量作为索引 [英] Using Integer Variable as Index in scanf

查看:82
本文介绍了在scanf中使用整数变量作为索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在函数中执行以下操作,但始终遇到分段错误错误.当我尝试使用[iModify - 1]作为索引时失败了.

I'm trying to do the below in my function but keep getting a segmentation fault error. It's failing when I'm trying to use [iModify - 1] as my index.

您不能将int变量计算用作C中的索引吗?

Can you not use an int variable calculation as an index in C?

int modify(pb *PhoneBook)
{
   int x;
   int iModify = 0;
   char name_num[] = {'\0'};
   print(PhoneBook);
   printf("\nWhich entry would you like to modify? ");
   scanf("%d", &iModify);
   printf("\niModify - 1: %d\n", iModify - 1);

   printf("\nModify name or number? ");
   scanf("%s", name_num);
   convert_u(name_num);
   if (strcmp(name_num, "NAME") == 0) {
      printf("\nEnter new name: ");
      scanf("%s %s", PhoneBook[iModify - 1].cFirstName, PhoneBook[iModify - 1].cLastName); //fails here
   }
   else if (strcmp(name_num, "NUMBER") == 0) {
      printf("\nEnter new number: ");
      scanf("%s", PhoneBook[iModify - 1].cNumber); //also fails here
   }
}

推荐答案

这里的问题是

 char name_num[] = {'\0'};

此处,name_num的长度为1 char,这不足以在以后保留 string .所以,当你这样做

here, name_num is having a length of 1 char, which will not be sufficient for holding a string at a later point. So, when you do

scanf("%s", name_num);

您实际上是在写越界,从而调用未定义行为.

you're essentially writing out of bound which invokes undefined behavior.

参考:C11,第§6.7.9章

Reference: C11, chapter §6.7.9

如果初始化了一个未知大小的数组,则其大小由索引最大的数组确定 带有显式初始化程序的元素. [...]

If an array of unknown size is initialized, its size is determined by the largest indexed element with an explicit initializer. [...]

为了与您的代码进行比较,name_num是一个未知大小的数组,该数组仅由括号括起的初始化程序中的单个元素初始化,因此该数组的大小为1.

To compare with your code, name_num is an array of unknown size which is being initialized by only a single element in a brace enclosed initializer, so the size of the array will be 1.

解决方案:您必须在定义时明确提及尺寸.您将需要类似

Solution: You have to mention the size explicitly at the time of definition. You'll be needing something like

char name_num[32] = {'\0'};     //32 is just for example purpose
....
scanf("%31s", name_num);  // make sure longer inputs don't blow up the buffer

或类似的

话虽如此,请注意您的int modify()函数没有 return任何值.如果在调用方中使用了返回值,它将再次调用未定义行为.

Having said that, please notice your int modify() function does not return any value. If the returned value is used in the caller, it will again invoke undefined behavior.

这篇关于在scanf中使用整数变量作为索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆