0

Below I have two code samples. In the first I can only work with the dot . operator and in the second I can only work with the arrow -> operator. But why? Do I not have in both cases pointers?

The code for arrow -> operators:

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

typedef struct{
    double **plist;
} ParticleList;

void sendPar(ParticleList *pl, int *n, int np){
    pl -> plist = malloc(sizeof(double*) * np);
    for(int p=0; p<np; p++){
        pl->plist[p] = malloc(sizeof(double) * n[p]);
    }

    for(int p=0; p<np; p++){
        for(int k=0; k<n[p]; k++){
            pl->plist[p][k] = k+1;
        }
    }
}

int main(){
    ParticleList pl;
    int np = 3;
    int n[np];
    n[0] = 2;
    n[1] = 4;
    n[2] = 7;   
    sendPar(&pl, n, np);
}

The code for dot . operators:

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

typedef struct{
    double **plist;
} ParticleList;

void sendPar(int *n, int np){
    ParticleList pl;
    pl.plist = malloc(sizeof(double*) * np);
    for(int p=0; p<np; p++){
        pl.plist[p] = malloc(sizeof(double) * n[p]);
    }

    for(int p=0; p<np; p++){
        for(int k=0; k<n[p]; k++){
            pl.plist[p][k] = k+1;
        }
    }
    free(pl.plist);
}

int main(){
    int np = 3;
    int n[np];
    n[0] = 2;
    n[1] = 4;
    n[2] = 7;
    sendPar(n, np);
}

Are both versions valid or is there any difference?

Gilfoyle
  • 3,282
  • 3
  • 47
  • 83

2 Answers2

2

In the 1st case, you do are using a pointer; thus using the arrow operator -> is correct:

void sendPar(ParticleList *pl, int *n, int np){
    pl->plist

In the 2nd case, you are NOT using a pointer but a value; thus using the DOT . operator is correct (necessary):

ParticleList pl;
pl.plist =

That's it — except that you don't put spaces around either the dot or arrow operator.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Tytou
  • 31
  • 2
1

In the first example, pl is a pointer of type ParticleList. To dereference the members of a struct type pointer you use the ->.

In your second code example, pl is a struct of ParticleList, not a pointer. To dereference struct members, you use a dot.

David Hoelzer
  • 15,862
  • 4
  • 48
  • 67