-1

I have been programming with GCC for a while but I decided to start working with Visual Studio instead, because it is comfortable. Anyways, the problem is that in Visual studio, dynamic arrays do not really work like they do in GCC, so i used malloc instead.

When printing the 1st value assigned I will get a correct answer. However, the next values will be wrong, the 2nd value will always be wrong, the third value wrong and I can not figure out why.

For example, when inserting 1,2,3 and try to print the 2nd spot, it gives 5.

int main(void)
{
 K1();
 printf("%d\n", p1+1);
 return 0;
]

With p1[i] the program crashes. p1, is int *

void K1(void)
{

 int i;

 printf("n1");
 scanf_s("%d", &n1);

 p1 = (int*)malloc(sizeof(int) * n1);

 for(i=0;i<n1;i++)
 {
    scanf_s("%d", &p1 + i*sizeof(int));
 }
}

I can not figure out what is the problem.

s3v3ns
  • 198
  • 1
  • 17

1 Answers1

4

This line:

scanf_s("%d", &p1 + i*sizeof(int));

should just be:

scanf_s("%d", p1 + i);

or better still:

scanf_s("%d", &p1[i]);


You also have a bug in your printf statement here:
printf("%d\n", p1+1);

This should be:

printf("%d\n", *(p1+1));

or better still:

printf("%d\n", p1[1]);

Also note that you should not cast the result of calls such as malloc in C, so:

p1 = (int*)malloc(sizeof(int) * n1);

should be:

p1 = malloc(sizeof(int) * n1);

or better still:

p1 = malloc(n1 * sizeof(*p1));
Community
  • 1
  • 1
Paul R
  • 208,748
  • 37
  • 389
  • 560
  • Why do you say `&p1[i]` is better than `p1 + i`? – cadaniluk Oct 12 '15 at 12:12
  • @PaulR Yes, the scanf_s("%d", &p1 + i*sizeof(int)); is a fluke from copying. Ah i feel freaking stupid for asking this question, can not believe i did not see that – s3v3ns Oct 12 '15 at 12:13
  • @cad: I would say the array notation provides a clearer representation of the programmer's intent, but it's a matter of personal preference/style, and I know some people still like to think in terms of pointers and offsets. – Paul R Oct 12 '15 at 12:14