Basic C Questions

Status
Not open for further replies.

newton_meter

Ars Scholae Palatinae
1,424
Level_7, what you were saying is so clearly wrong, that I didn't even bother looking at your code until this morning. Funny, funny stuff.

Originally posted by Level_7:
Code:
#include <stdio.h>
int main(void)
{
	register int* reg1 asm("a5");
	int x = 5;
	*((unsigned int*)reg1) = x;
	printf("The value of reg1 is %d", *reg1);
}

I compiled using gcc for 68K and ran it on my Coldfire sitting beside me. You should be able to use all the registers this way. You should also be able to compile on an Intel machine using AH, AX etc. However, I do think there are certain registers that are safer to use than others.
Originally posted by Level_7:
I was referring to your code that you posted, not my statement. I can write to any register with my code snippet above, and read that value at a later time; its a global register variable. What's your point?

Um, you didn't write to a register at all. You declared that the (uninitialized) value in the register pointed to somewhere in memory that was an int. Then you crammed a 5 in there (memory), wherever it happened to be. I'll take your word that you actually did run this. That it worked was sheer luck.

I repeat, you didn't write to a register at all, you wrote to wherever in memory that (uninitialized) value pointed to. Wanna see what happened when I ran it (after changing "a5" to a register name on my machine)?

Code:
Segmentation fault (core dumped)

I guess that's what happens when "engineers" program.
 

gaffa

Well-known member
6,210
OK Peter. I see what you are saying in the 'pure' C sense.
My mistake is that I have mapped what C is doing onto what I already knew. I understand what it is doing within the terms of my past experience, but I can see how my terminology would confuse the issue for others, and I apologise for that.

Cheers

Gaffa.

BTW, the ASCII art does deserve a nomination. Especially considering that whenever I have attempted to do something similar on these fora, I have abandoned it.
 

Tristram

Ars Scholae Palatinae
1,428
Subscriptor
Ummm, I don't want to beat a dead horse, but the reason why you use & in the scanf("...", &i, ...); is becase scanf expects pointers (i.e., addresses) after the format string. Now what Nm and PeterB said is true about why the function needs the address, what the user needs to do is meet the contract of the function call he is trying to make.

Now, it is possible to manage your own memory with this, ala

Code:
int *pi;
pi = (int *)malloc(sizeof(*pi));
scanf("%d", pi);
...
free(pi);

but it is much easier and safer (and faster) to let the compiler use automatic variables to hold the results. The & <handwaving> simply returns the equivalent of 'pi'</handwaving> in the preceding code snippet.
 
Status
Not open for further replies.