尝试混合一些字符串时出现意外的分段错误

时间:2018-03-26 14:47:39

标签: c

我需要以这种方式操纵字符串:

如果角色是' +'或者' - '或者' /'或者' *',将它们移动到缓冲区的末尾,如果没有,则移动到缓冲区的开头。

我的解决方案很简单:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void mix_the_string(char ** buff, char ** string)
{
    printf("The string which will be printed is : %s\n",*string);

    int i = 0;
    int j = strlen(*string) - 1;

    while(i< strlen(*string))
    {
        if(*string[i] != '+' || *string[i] != '-' || *string[i] != '*' || *string[i] != '/')
        {

            printf("in the first if, i = %d, *string[i] = '%d'\n",i,(int)*string[i]);

            *buff[i] = *string[i];
        }
        else
        {
            printf("in the second if, i = %d, *string[i] = '%d'\n",i,(int)*string[i]);
            *buff[j] = *string[i];
        }

        i++;
        j--;
    }
}

int main()
{    
    char * buff  = (char *) malloc(50);
    char * string  = (char *) malloc(50);

    string = "1+2+3";

    mix_the_string(&buff,&string);
    puts(buff);
    free(buff);
    free(string);

    return 0;
}

此代码的输出为:

 The string which will be printed is : 1+2+3
 in the first if, i = 0, *string[i] = '49'
 in the first if, i = 1, *string[i] = '49'
 Segmentation fault

我期望这个例子输出如下:

The string which will be printed is : 1+2+3
in the first if, i = 0, *string[i] = '49'
in the second if, i = 1, *string[i] = '43'
in the first if, i = 2, *string[i] = '50'
in the second if, i = 3, *string[i] = '43'
in the first if, i = 4, *string[i] = '51'
123++

我哪里错了?

2 个答案:

答案 0 :(得分:5)

[HttpPost] [AllowAnonymous] public ActionResult VerifyPayment( VerifyResult Vresult ) { try { if ( !string.IsNullOrEmpty(Request.Form["transId"]) ) { Payment ob = new Payment(); string result = ob.verify(Request.Form["transId"].ToString()); JsonParameters Parmeters = JsonConvert.DeserializeObject<JsonParameters>(result); if ( Parmeters.status == 1 ) { var userId = User.Identity.GetUserId(); var user = db.Users.Where(u => u.Id == userId).FirstOrDefault(); user.SuccessfullPayment = true; user.FactorNo = User.Identity.GetUserId(); user.TraceNo = Request.Form["traceNumber"]; user.TransId = int.Parse(Request.Form["transId"]); user.CardNo = Request.Form["cardNumber"]; user.PurchasedDate = DateTime.Now; user.State = Parmeters.status; user.Message = Request.Form["message"]; db.Entry(user).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); Vresult.success = true; Vresult.TransActionID += Request.Form["transId"].ToString(); Vresult.Amount += Parmeters.amount.ToString(); Vresult.SuccessMessage = "successful payment"; return RedirectToAction("Index", "DownloadEbook", new { traceNumber = user.TraceNo , factorNumber = user.FactorNo, purchaseDate =Utils.Funcs.ObtainPersianDate( (DateTime)user.PurchasedDate ) }); } else { Vresult.error = true; Vresult.ErrorMessage = "error code " + Parmeters.errorCode + "<br />" + "Errr meesafe " + Parmeters.errorMessage; } } } catch ( Exception ex ) { Vresult.error = true; Vresult.ErrorMessage = ex.Source+"\t"+ex.InnerException + "\t" + ex.Message+"ERRR"; } return View(new AllNeededModels() { VerifyResult = Vresult }); *string[i]表示法之间存在差异。 (*string)[i]的优先级高于[]运算符。您通过指针将字符串传递给指针,因此您应该在代码的每一行中调用*

  

(*string)[i]表示 - 取消引用指向数组的指针并获取字符串数组的(*string)[i]元素

现在你正在做

  

i-th - 获取字符串数组的*string[i]元素(!!但这不是数组,这只是一个元素)并且取消引用第一个元素

i-th执行相同操作。

buff函数中,您应该将 1 + 2 + 3 字符串文字复制到main缓冲区中,例如string函数。

答案 1 :(得分:0)

您的代码中存在很多错误。

  • 首先string = "1+2+3";然后执行free(string)不正确。 首先使用strcpy(string,"1+2+3");复制它然后                     free(string)
  • stringmix_the_string()中的双指针。访问*string[i]之类的内容不正确,因为string不是array of pointer。而不是使用*(*string+i)。同样适用于buf
  • 最后不需要施放malloc。只需char * buff = malloc(50);即可。
  • 此外,您不需要将&string传递给mix_the_string()。只需通过string就够了。

这是您想要的预期代码

void mix_the_string(char ** buff, char ** string)
{
    printf("The string which will be printed is : %s\n", *string);

    int i = 0;
    int j = strlen(string[0]) - 1;

    while (i < strlen(string[0]))
    {
        if (*(*string + i) != '+' || *(*string + i) != '-' || *(*string + i) != '*' || *(*string + i) != '/')
        {
            printf("in the first if, i = %d, *string[i] = '%d'\n", i, *(*string + i));

            *(*buff + i) = *(*string + i);
        }
        else
        {
            printf("in the second if, i = %d, *string[i] = '%d'\n", i, *(*string + i));
            *(*buff + j) = *(*string + i);
        }
        i++;
        j--;
    }
}

int main()
{
    char * buff = (char *)malloc(50);
    char * string = (char *)malloc(50);

    strcpy(string, "1+2+3");

    mix_the_string(&buff, &string);
    puts(buff);
    free(buff);
    free(string);

    return 0;
}