需要帮助C程序

时间:2015-10-28 03:46:35

标签: c arrays loops pointers

对于作业,我正在编写代码,计算计算2个掷骰子总和的次数...例如,如果骰子1是5而骰子2是6,那么timesRolled的值[(模具1) + die 2)]将递增。代码如下,这证明了我的逻辑。返回的值是垃圾,我需要帮助确定我在哪里出错了。提前谢谢!

function sendJSONtoServer() {
		//alert("the call start was success to sendJSONtoServer");
		$.ajax({
			url: 'http://myserver.edu/~sas0090/save-userinfo.php',
			data: {'message' : "Hey Hi"},
			type: 'GET',
			dataType:'json',
			crossDomain: true,
			contentType: "application/json; charset=utf-8",
			success: function(data) {
			//it works, do something with the data
			alert('Your comment was successfully added');
			},
			error: function() {
			//something went wrong, handle the error and display a message
			alert('There was an error adding your comment');
			}
		});
		alert("the call end was success to sendJSONtoServer");
}

2 个答案:

答案 0 :(得分:2)

你宣布:

int timesRolled[] = { 0 };

这会创建一个长度为timesRolled的数组1。但是在for循环中你正在递增

++timesRolled[(rollTotal)];

如果rollTotal大于0,则会导致缓冲区溢出。因为那时您正在尝试访问未定义的数组元素。那会引导你Undefined Behavior

同样会在printf()中发生:

printf("%ds: %d\n", pointerVal, timesRolled[(pointerVal)]);

首先确定timesRolled最大长度。然后声明并初始化它。例如:

int timesRolled[13] = { 0 }; //timesRolled is now an array of length 13

答案 1 :(得分:2)

您正在访问未定义为数组大小的数组元素1pointerVal<=12

for (pointerVal = 1; pointerVal <= 12; ++pointerVal) {
            printf("%ds: %d\n", pointerVal, timesRolled[(pointerVal)]);

替换:

int timesRolled[] = { 0 } int timesRolled[13] = { 0 }

骰子的总和最多为12。